当找到特定字符串(实体)时,我使用以下代码删除表中的行。它工作正常但如果"实体"它会失败。在数据库中不存在。
using (OleDbConnection thisConnection = new OleDbConnection(connectionname))
{
string deletequery = " DELETE FROM SFModelOutputVariables WHERE [Entity] = '" + ENTITY + "'";
OleDbCommand myAccessCommandDelete = new OleDbCommand(deletequery, thisConnection);
try
{
thisConnection.Open();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString() + "\n" + "-Error found while " + "connecting to Access Database");
return;
}
myAccessCommandDelete.ExecuteNonQuery();
thisConnection.Close();
}
当表格中不存在所选实体的数据时,我遇到了行myAccessCommandDelete.ExecuteNonQuery();
的错误。
答案 0 :(得分:1)
您需要检查实体是否存在。如果实体存在,则运行删除,但如果不存在,则可能会向用户返回404或显示相应的消息。
using (OleDbConnection thisConnection = new OleDbConnection(connectionname))
{
string cmdStr = "Select count(*) from SFModelOutputVariables WHERE [Entity] = '" + ENTITY + "'";
OleDbCommand cmd = new OleDbCommand(cmdStr, thisConnection);
int count = (int)cmd.ExecuteScalar();
if(count == 0)
{
MessageBox.Show("Sorry no entity was found :-(");
return;
}
// write your code for removing things here....
}
答案 1 :(得分:1)
您可以使用executioncalar方法,它给出表的行数。如果它的> 0您可以执行删除操作。
MSDN ExecuteScalar方法样本