OLEDB例外| INSERT INTO语句中的语法错误

时间:2017-07-16 05:16:39

标签: c# ms-access oledb insert-into oledbcommand

我正在尝试制作注册页面。我使用的数据库是Microsoft Access。但是当我想在表格中添加一些东西时,我得到了这个例外:

  

INSERT INTO语句中的语法错误

这是我的代码:

        try
        {
            string ApplicationPath = Application.StartupPath;
            System.Data.OleDb.OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ApplicationPath + "\\data1.accdb");
            System.Data.OleDb.OleDbCommand command = connection.CreateCommand();
            command.CommandText = "INSERT INTO tblK(K, Comp, Price, Num) VALUES ('" + txtName.Text + "', '" + txtCompany.Text + "', '" + txtPrice.Text + "', '" + txtNumber.Text + "')";
            command.CommandType = System.Data.CommandType.Text;
            connection.Open();
            command.ExecuteNonQuery();
            MessageBox.Show("The data have been processed successfully", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

  cmd.CommandText = "INSERT INTO tblK(K, Comp, Price, Num) VALUES ('@k','@comp',...)";
    //Assign values as `parameter`. It avoids `SQL Injection`
    cmd.Parameters.AddWithValue("@k", txtName.Textt);
    cmd.Parameters.AddWithValue("@comp", txtCompany.Text);
    .
    .

并检查您的K,Comp,Price和Num列!! ...并确保您的数据库中的所有数据类型都是nvarchar(..)(或访问中的某些类型)。因为您将查询与它们绑定的所有值都是string键入的