简体   繁体   中英

Adding error handling to deleting a user from a database

I want to add error handling to my code so that if the username and password cannot be found inside of my database it comes up with an error message. I don't have much experenice using try...catch My code for deleting user from db works fine, this is what I use:

string constring = databaselocation
SqlConnection conData = new SqlConnection(constring);
SqlCommand cmdData = new SqlCommand(query, conData);
SqlDataReader myReader;  
try
{
    conData.Open();
    myReader = cmdData.ExecuteReader();
    MessageBox.Show("member has been deleted");
    while (myReader.Read())
    {

    }

}
catch (Exception)
{
    MessageBox.Show(" ");
}

thanks for any help guys

I don't have the text of your query, but if it's a simple DELETE statement, you could try something like this:

var myAffectedRows = cmdData.ExecuteNonQuery();
if (myAffectedRows > 0)
{
    MessageBox.Show("Something was deleted");
}
else
{
    MessageBox.Show("Nothing was deleted");
}

However your question and your code doesn't match but what I can understand from your code you need something like this

string constring = databaselocation
SqlConnection conData = new SqlConnection(constring);
SqlCommand cmdData = new SqlCommand(query, conData);
SqlDataReader myReader;  
try
{
    conData.Open();

    // I am assuming here you are trying to access user/password
    myReader = cmdData.ExecuteReader();

    // and then you want to verify if you receive any row for that combination
    if(myReader != null && myReader.HasRows)
    {
        // then your record deletion code should go here
        // ...
        // ...

        MessageBox.Show("member has been deleted");
    }
    else
    {
         throw new Exception("Username and password is wrong! Cannot delete record");
    } 

}
catch (Exception e)
{
    MessageBox.Show(e.Message);
}

Note : This is not the best way to achieve this but I just wanted to write the code using try.. catch... which you mentioned specifically. There is no actual need of try... catch here

A case of "user record cannot be found" is a logic error. In general, SqlClient will not produce an exception if a certain record cannot be found. So you can't catch it in a catch block.

However, SqlClient will produce an exception if an object such as Table, View etc. cannot be found or you have Syntax error in your query. You can check MSDN for all possible SqlClient Exceptions.

Although, ExecuteReader() can execute DELETE query, you don't need a result set. It is a better approach to use ExecuteNonQuery() . This method returns a integer which tells you how many records affected by executing your query.

To handle "record cannot be found" you need to implement your own logic. For example, the following code will delete a record with given ID, if cannot delete it will fire an exception.

private void DeleteUser(int userId)
{
    string deleteCommandText = @"DELETE FROM MyUsers WHERE Id = @id";
    using(SqlConnection conn = new SqlConnection("your_connection_string_here"))
    {
        if(conn.ConnectionState != ConnectionState.Open) conn.Open();
        using(SqlCommand cmd = new SqlCommand())
        {
           cmd.Connection = conn;
           cmd.CommandText = deleteCommandText ;
           cmd.Parameters.AddWithValue("@Id", userId);

           int resultRowCount;
           resultRowCount = cmd.ExecuteNonQuery();

           if(resultRowCount <= 0)
               throw new UserNotFoundException("Cannot delete User record, no record found");
        }
        if(conn.ConnectionState != ConnectionState.Closed) conn.Close();
    }
}

Additionally you can define your own Exceptions, such as UserNotFoundException. Check this MSDN page for example and more info.

An example of UserNotFoundException

using System;

public class UserNotFoundException: Exception
{
    public UserNotFoundException()
    {
    }

     public UserNotFoundException(string message)
    : base(message)
    {
    }

    public UserNotFoundException(string message, Exception inner)
    : base(message, inner)
    {
    }
}

Now you can enclose call to this method in a try...catch block and show a MessageBox in catch block. Example:

private void deleteUser_Click(object sender, EventArgs e)
{
    try
    {
        DeleteUser(userId: 5);
        MessageBox.Show("User deleted");
    }
    catch(UserNotFoundException ex)
    {
        MessageBox.Show("Cannot delete user");
    }
}

Finally

Try to avoid throwing exceptions(custom or not) when your error is not critical to application logic, as exceptions carry StackTrace and bunch of other data with them, they affect application execution performance.

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