如何在c#中使用if条件执行SQL
本文关键字:if 条件 执行 SQL | 更新日期: 2023-09-27 18:10:50
如何在c#中执行SQL与if条件?
这是我的查询,我执行这个查询,我得到一个错误说"无效的SQL语句;期望'DELETE', 'INSERT', 'PROCEDURE', 'SELECT'或'UPDATE'。"我使用MS ACCESS作为后端
mycon.ConnectionString = ConnString;
mycon.Open();
string mySelectQuery = "IF (EXISTS (SELECT * FROM Employee AS t1 WHERE t1.ssn ='"+textBox4.Text+"' "+
"))begin UPDATE Employee SET "+
"fname ='"+textBox1.Text+"' ,"+
"minit ='"+textBox2.Text+"' ," +
"lname ='" + textBox3.Text+"', " +
"ssn ='" +textBox4.Text+"', " +
"bdate ='" +textBox5.Text+"', " +
"address ='" +textBox6.Text+"', " +
"sex ='" +textBox7.Text+ "', " +
"salary ='" +textBox8.Text+"', " +
"superssn ='" +textBox9.Text+"', " +
"dno ='" +comboBox2.Text+"'" +
" WHERE ssn = '"+textBox4.Text+"' "+
"end "+
"else "+
" begin "+
" INSERT INTO employee values ('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"','"+textBox8.Text+"','"+textBox9.Text+"','"+comboBox2.Text+"')"+
" end";
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, mycon);
int Success= myCommand.ExecuteNonQuery();
MS Access不支持IF
语句。不是else
也不是begin
。您必须在c#代码中执行此操作,例如首先执行"SELECT * FROM Employee AS t1 WHERE t1.ssn ='"+textBox4.Text + "'";
查询,然后如果有结果则执行下一个查询。
此外,您应该使用参数化查询或转义文本框的值。
似乎你想要发生的是UPDATE
记录,如果它在数据库中Exists
,否则INSERT
记录。
您不能在一个查询中完成此操作,因此如果记录存在,请准备一个查询以便在数据库中查找,然后使用输出(isExists或not)到UPDATE
或INSERT