Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One a DELETE query, how to know that there was nothing to delete?

Tags:

c#

.net

sql

select

I'm currently polishing a C# app in relation with a SQL-Server base.

It's quite simple, you can add or remove entries from the SQL table via some fields from the application.

Question is : On a Delete action, I've made this kind of query :

DELETE FROM table 
 WHERE ID = @ID 

It deletes what I ask it to delete, BUT what if the query doesn't find anything in the DB ? How can I detect that ? Because in this case, the application deletes nothing, and no exception is raised. To make it short, I'd just like to tell the user that there's nothing to delete in this case.

like image 281
Jan Avatar asked Dec 04 '22 14:12

Jan


1 Answers

If you are using SqlCommand object, there is a method called ExecuteNonQuery. The method return how many rows are affected. So, zero means none.

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        int rowsAffected = command.ExecuteNonQuery(); // <== this
    }
}
like image 97
John Woo Avatar answered Dec 08 '22 05:12

John Woo