尝试从数据库中删除行时“条件表达式中的数据类型不匹配”

时间:2012-09-18 09:52:38

标签: c# oledb

    OleDbCommand system = new OleDbCommand();
    system.CommandType = CommandType.Text;
    system.CommandText = "DELETE FROM Student WHERE(ID= '" + 
                          txtStudentIDnumber.Text + "')";
    system.Connection = mydatabase;

    mydatabase.Open();
    system.ExecuteNonQuery();
    dataGridView1.Update();

    this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
    mydatabase.Close();

    MessageBox.Show("Student Record Deleted.", "deleting record...");

3 个答案:

答案 0 :(得分:2)

在命令文本中,您需要删除(')周围的单引号txtStudentIDnumber.Text,因为它看起来ID是整数类型,并且您将其作为字符串传递。以下应该修复错误。

system.CommandText = "DELETE FROM Student WHERE(ID= " + txtStudentIDnumber.Text + ")";

编辑:关于@mdb评论,您应该始终在查询中使用Parameters,这样就可以避免SQL Injection。请考虑以下事项:

OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID = ?";
OleDbParameter parameter = new OleDbParameter("ID", txtStudentIDnumber.Text);
system.Parameters.Add(parameter);
system.Connection = mydatabase;

mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();

答案 1 :(得分:2)

OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID=@ID";
system.Parameters.AddWithValue("@ID", txtStudentIDnumber.Text);
system.Connection = mydatabase;

mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();

this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();

MessageBox.Show("Student Record Deleted.", "deleting record...");

答案 2 :(得分:1)

txtStudentIDNumber的用户输入为

时会发生什么
1 or 1=1

在这种情况下,硬编码的SQL字符串将是

DELETE FROM Student WHERE(ID=1 or 1=1)

所以更喜欢参数化 sql语句而不是硬编码字符串。

using(OleDbConnection cn=new OleDbConnection(cnStr))
 {
  using(OleDbCommand cmd=new OleDbCommand())
   {
    cmd.CommandText="DELETE FROM Student WHERE ID=@ID";
    cmd.Connection=cn;
    cmd.Parameters.Add("@ID",SqlDbType.Int).Value=txtStudentIDnumber.Text;
    cn.Open();
    cmd.ExecuteNonQuery();
    cn.Close();
   }
 }