当找到特定的字符串(实体(时,我使用以下代码删除表中的行。它工作正常,但如果数据库中不存在"实体",则会失败。
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();
错误。
您需要检查实体是否存在。如果实体存在,则运行删除,但如果不存在,则可能向用户返回 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....
}
您可以使用 executescalar 方法,它给出表的行数。 如果> 0,则可以执行删除操作。
MSDN执行标量方法示例