c# - 在 C# 中使用 sqlcommand 执行查询时出错

标签 c# visual-studio-2012 web-applications sql-server-2012

这是我的代码:

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/

相关文章:

visual-studio-2012 - 了解我正在哪个分支和哪个工作区工作的最佳方法是什么

javascript - 为什么我们需要客户端和服务器端验证?

c# - 无法使用 EntityFramework.IBM.DB2 连接到 Informix

c# - 按钮 FontWeight 不起作用

visual-studio-2012 - 为什么我无法打开 VS 项目

asp.net - 如何在同一解决方案中从 MVC 项目调试 Web API 项目

javascript - 使用 AngularJS 向 KDB+ 进程发送 HTTP GET 请求

web-applications - 如何通过单击推送通知启动 PWA(渐进式 Web 应用程序)打开?

c# - Application.Exit() 与 Application.ExitThread() 与 Environment.Exit()

c# - 我如何在 SQL 中使用枚举而不在我的 SQL 脚本/过程中硬编码魔数(Magic Number)?