从c#到Access DB的INSERT STATEMENT中的语法错误

时间:2015-07-01 23:44:03

标签: c# database ms-access

 con.Open();
        cmd = new OleDbCommand("insert into login (user, password) values ('" +textBox1 .Text + "','" + textBox2 .Text + "');",con);
        cmd.CommandType = CommandType.Text;
        int temp = cmd.ExecuteNonQuery();
        if (temp > 0)
        {
           textBox1.Text = null;
            textBox2.Text = null;
            MessageBox.Show("Record Successfuly Added");
        }
        else
        {
            MessageBox.Show("Record Fail to Added");
        }
        con.Close();

当我尝试插入一些错误时出现(INSERT STATEMENT中的语法错误) 我尝试不同的方法来像参数或直接的值 PLZ!

1 个答案:

答案 0 :(得分:2)

  • 转义保留关键字user
  • 使用参数化查询
  • 避免sql注入
  • 使用一次性物品

尝试这种方法:

using (OleDbConnection con = new OleDbConnection(connectionString))
{
    con.Open();
    using (var cmd = new SqlCommand(
    "insert into login ([user], [password]) values (@user, @pass);",
    con))
    {
        cmd.Parameters.Add(new OleDbParameter("@user", textBox1.Text ));
        cmd.Parameters.Add(new OleDbParameter("@pass", textBox1.Text ));

        if (temp > 0)
        {
            textBox1.Text = String.Empty;
            textBox2.Text = String.Empty;
            MessageBox.Show("Record Successfuly Added");
        }
        else
        {
            MessageBox.Show("Record Fail to Added");
        }
    }
}