【问题标题】:Getting Syntax Error When using 'Insert into' command in c#在 C# 中使用“插入”命令时出现语法错误
【发布时间】:2017-02-06 05:25:37
【问题描述】:

使用 c# 使用“插入”SQL 命令时出现语法错误。我正在使用 Access db 来存储一些数据。 令人惊讶的是,当我将确切的命令复制到 MS Access 中以尝试它是否不正确时,它就像魅力一样。我有点困惑!我感谢这方面的任何想法或帮助。这是我的代码:

using (OleDbConnection connection = new OleDbConnection(Global.ConString))
            {
                using (OleDbCommand command = new OleDbCommand())
                {
                    command.Connection = connection;            
                    command.CommandType = CommandType.Text;
                    command.CommandText = "INSERT INTO Users(Name,UserName,Password,Customers,Jobs,Invoice,Statement,Reports,Users) values (@name,@UserName,@Password,@Customers,@Jobs,@Invoice,@Statement,@Reports,@Users)";

                    command.Parameters.AddWithValue("@name",fullName.Text );
                    command.Parameters.AddWithValue("@UserName", userName.Text);
                    command.Parameters.AddWithValue("@Password", passWord.Text);
                    command.Parameters.AddWithValue("@Customers", Customers.Checked);
                    command.Parameters.AddWithValue("@Jobs", Jobs.Checked);
                    command.Parameters.AddWithValue("@Invoice", Invoice.Checked);
                    command.Parameters.AddWithValue("@Statement", Statement.Checked);
                    command.Parameters.AddWithValue("@Reports", Report.Checked);
                    command.Parameters.AddWithValue("@Users", userDef.Checked);

                    try
                    {
                        connection.Open();
                        int recordsAffected = command.ExecuteNonQuery();
                        if (recordsAffected > 0)
                        {
                            foreach (Control item in newRecord.Controls)
                            {
                                if (item is TextBox) item.ResetText();
                            }
                            timer1.Enabled = true;

                        }
                        else
                            MessageBox.Show("Insert Fail");

                    }
                    catch (OleDbException err)
                    {

                        MessageBox.Show("Somthing wrong. Error no. is: " + err.ErrorCode + "..." + err.Message);
                    }
                }
            }

【问题讨论】:

    标签: c# sql ms-access syntax-error sql-insert


    【解决方案1】:

    您的问题很可能是使用保留字作为标识符,特别是“密码”。将该列名称括在括号中,即[Password],您应该一切顺利。

    如果可能,最好避免使用保留字。一般来说,您不应该在数据库中存储未经哈希处理的密码,因此像“PasswordHash”这样的列名是合适的并且可以避免这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-14
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多