这是我的代码:
string createString = "CREATE TABLE user (uid INT PRIMARY KEY IDENTITY(1,1), uname NVARCHAR(30), uemail NVARCHAR(30), upass NVARCHAR(20), ucontact INT(10))"; //YOUR SQL COMMAND TO CREATE A TABLE
SqlConnection connection = new SqlConnection("Data Source=DELL\\SQLEXPRESS;Integrated Security=True;Connect Timeout=1000000;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
SqlCommand create = new SqlCommand(createString, connection);
connection.Open();
create.ExecuteNonQuery();
connection.Close();
我收到以下错误:
Incorrect syntax near the keyword 'user'
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'user'.
最佳答案
用户
是 reserved keyword在 T-SQL 中。您需要将它与方括号一起使用,例如 [user]
作为最佳实践,将其更改为非保留字。
也可以使用 using
statement自动处理您的连接和命令,而不是手动调用 Close
方法。
using(var connection = new SqlConnection(connectionString))
using(var create = connection.CreateCommand())
{
create.CommandText = "...";
connection.Open();
create.ExecuteNonQuery();
}
关于c# - 在 C# 中使用 sqlcommand 执行查询时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31670548/