![](/img/trans.png)
[英]C# - Microsoft sql database | Can't add new user on my e-contact app
[英]I can't add text to sql database on c#
我无法从SQL数据库的网站添加文本
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString);
String insert = "INSERT INTO dbo.Table (Name,Surname,Email,Mobile,Telephone) VALUES (@name,@surname,@email,@mobile,@telephone)";
SqlCommand command = new SqlCommand(insert, connection);
command.Parameters.AddWithValue("@name", Name.Text);
command.Parameters.AddWithValue("@surname", Surname.Text);
command.Parameters.AddWithValue("@email", Email.Text);
command.Parameters.AddWithValue("@mobile", Mobile.Text);
command.Parameters.AddWithValue("@telephone", Telephone.Text);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
它向我显示此错误的“ /”应用程序中的服务器错误。 关键字“表格”附近的语法不正确。
说明:执行当前Web请求期间发生未处理的异常。 请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息。
异常详细信息:System.Data.SqlClient.SqlException:关键字'Table'附近的语法不正确。
源错误:
Line 25: command.Parameters.AddWithValue("@telephone", Telephone.Text);
Line 26: connection.Open();
Line 27: command.ExecuteNonQuery();
Line 28: connection.Close();
Line 29: }
在第27行出现错误,请帮助我...
数据库服务器告诉您在不应该出现的地方使用了关键字Table
。 通过将其包装在括号中,您可以使数据库服务器确信Table
是Table
的名称: [Table]
。
编辑:如果您使用的是MySQL,则可能要使用
String insert = "INSERT INTO `Table` (Name,Surname,E...
代替。
首先,请注意SqlConnection
是SQL Server的ADO.Net客户端,而不是MySQL。 如果确实需要连接到MySQL,则需要: MySqlConnection
。
确保“ 表”是表的实际名称。 如果是这样,请像下面那样逃避它: [表]
另外,不要忘记配置连接:
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString))
{
String insert = "INSERT INTO [dbo].[Table] (Name,Surname,Email,Mobile,Telephone) VALUES (@name,@surname,@email,@mobile,@telephone)";
SqlCommand command = new SqlCommand(insert, connection);
command.Parameters.AddWithValue("@name", Name.Text);
command.Parameters.AddWithValue("@surname", Surname.Text);
command.Parameters.AddWithValue("@email", Email.Text);
command.Parameters.AddWithValue("@mobile", Mobile.Text);
command.Parameters.AddWithValue("@telephone", Telephone.Text);
connection.Open();
command.ExecuteNonQuery();
}
问题在于Table是SQL中的保留字。 因此,系统认为这是命令而不是表的名称。 如果要将表的名称更改为MyTable,则代码将正常工作(假设其他地方没有其他错误)。
此代码适用于测试数据库和更新的表名称:
INSERT INTO MyTable (Name,Surname,Email,Mobile,Telephone)
VALUES (@name,@surname,@email,@mobile,@telephone);
如果您想知道使用TSQL时应避免使用的单词,请参见以下指向MSDN的链接: https : //msdn.microsoft.com/zh-cn/library/ms189822.aspx
尽管按照另一位受访者的建议,您可以转义使用表名,但最好不要这样做。 这是一种非常不好的代码气味,以后可能导致许多其他问题和混乱。 取而代之的是,提供一个更有意义的名称并描述其内容-在您的示例和所提供的列的情况下,“联系方式”可能是更好的选择?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.