关键字“用户”附近的语法不正确
错误是:
System.Data.dll中发生了未处理的“System.Data.SqlClient.SqlException”类型exception
附加信息:关键字“用户”附近的语法不正确。
代码是:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFormsApplication1 { public partial class Form1 : Form { SqlConnection conn; SqlDataAdapter GameDA; SqlDataAdapter DetailDA; DataSet DetailDS; SqlCommandBuilder cmdBuilder; SqlDataAdapter UserDA; SqlDataAdapter AdministratorDA; SqlDataAdapter OrderDA; DataSet OrderDS; SqlCommandBuilder cmdBuilder2; public Form1() { InitializeComponent(); conn = new SqlConnection("Data Source=HOME-AC284121FE\\SQLEXPRESS;Initial Catalog=GameShop;Integrated Security=SSPI;"); SqlCommand command1 = new SqlCommand("SELECT * FROM Game", conn); GameDA = new SqlDataAdapter(command1); SqlCommand command2 = new SqlCommand("SELECT * FROM Detail WHERE GameID = @GameID", conn); command2.Parameters.Add(new SqlParameter("@GameID", SqlDbType.Int)); DetailDA = new SqlDataAdapter(command2); SqlCommand command3 = new SqlCommand("SELECT * FROM Administrator", conn); AdministratorDA = new SqlDataAdapter(command3); SqlCommand command4 = new SqlCommand("SELECT * FROM User", conn); UserDA = new SqlDataAdapter(command4); SqlCommand command5 = new SqlCommand("SELECT * FROM Order WHERE UserID = @UserID", conn); command5.Parameters.Add(new SqlParameter("@UserID", SqlDbType.Int)); OrderDA = new SqlDataAdapter(command5); cmdBuilder2 = new SqlCommandBuilder(OrderDA); cmdBuilder = new SqlCommandBuilder(DetailDA); } private void Form1_Load(object sender, EventArgs e) { DetailDS = new DataSet(); OrderDS = new DataSet(); GameDA.Fill(DetailDS, "Game"); **UserDA.Fill(OrderDS, "User"); // <-- Error** AdministratorDA.Fill(OrderDS, "Administrator"); comboBoxGame.DisplayMember = "Name"; comboBoxGame.ValueMember = "GameID"; comboBoxGame.DataSource = DetailDS.Tables["Game"]; dataGridView.DataSource = DetailDS.Tables["Detail"]; dataGridView.Columns["GameID"].Visible = false; dataGridView.Columns["DetailID"].Visible = false; } private void comboBoxGame_SelectedIndexChanged(object sender, EventArgs e) { if (comboBoxGame.SelectedValue != null) if (DetailDS.Tables.Contains("Detail")) { DetailDS.Tables["Detail"].Clear(); } DetailDA.SelectCommand.Parameters[0].Value = comboBoxGame.SelectedValue; DetailDA.Fill(DetailDS, "Detail"); } private void buttonExit_Click(object sender, EventArgs e) { this.Close(); } } }
User
是SQL Server中的内置函数。 您需要用方括号括起名称: [User]
。 这适用于碰巧与关键字,保留字或内置名称冲突的所有表名和其他用户定义的名称,因此我怀疑您还需要编写[Order]
,因为ORDER
是一个SQL关键字。
“用户”是SQL Server中的保留字 ,因此您必须使用分隔标识符来引用您的表。 尝试
SqlCommand command4 = new SqlCommand("SELECT * FROM [User]", conn);
相反…或将表重命名为未保留的内容。
(我还强烈建议您保持数据访问权限不受UI代码的影响,正确处理连接等……但这是另一回事。)