[英]Deleting a non-existent record from an Access database
I use the below code to DELETE a row in a table when a specific string(entity) is found. 当发现特定的字符串(实体)时,我使用下面的代码删除表中的一行。 It works fine but it fails if the "entity" does not exist in the database. 它可以正常工作,但是如果数据库中不存在“实体”,它将失败。
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();
}
I get an error for the line myAccessCommandDelete.ExecuteNonQuery();
我收到一行myAccessCommandDelete.ExecuteNonQuery();
的错误myAccessCommandDelete.ExecuteNonQuery();
when data for the selected entity does not exist in the table. 表中不存在选定实体的数据时。
You need to check if the entity exsists. 您需要检查实体是否存在。 Run the delete if the entity exsist but if it doesnt exsist possibly return a 404 to the user or display an appropriate message. 如果实体存在但不存在,则运行删除操作,可能会向用户返回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....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.