简体   繁体   中英

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(); 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.

    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....
 }

You can use executescalar method, its giving row count of table. if its > 0 you can perform delete operations.

MSDN ExecuteScalar method sample

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM