添加错误处理以从数据库中删除用户

时间:2021-05-03 15:40:34

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:

我想在我的代码中添加错误处理,这样如果在我的数据库中找不到用户名和密码,就会出现错误消息。我没有太多的尝试使用try ... catch我从db中删除用户的代码工作正常,这是我使用的:

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

谢谢你的帮助

3 个解决方案

#1


0  

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

我没有您的查询文本,但如果它是一个简单的DELETE语句,您可以尝试这样的事情:

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

#2


0  

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

注意:这不是实现此目的的最佳方法,但我只想使用try .. catch ...编写代码,具体提到。没有实际需要尝试...赶上这里

#3


0  

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.

“无法找到用户记录”的情况是逻辑错误。通常,如果找不到某个记录,SqlClient将不会产生异常。所以你无法在一个捕获块中捕获它。

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.

但是,如果无法找到Table,View等对象,或者查询中出现语法错误,SqlClient将产生异常。您可以检查MSDN以查找所有可能的SqlClient异常。

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.

虽然,ExecuteReader()可以执行DELETE查询,但您不需要结果集。这是使用ExecuteNonQuery()的更好方法。此方法返回一个整数,该整数告诉您执行查询所影响的记录数。

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.

要处理“无法找到记录”,您需要实现自己的逻辑。例如,以下代码将删除具有给定ID的记录,如果无法删除则会触发异常。

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.

此外,您可以定义自己的异常,例如UserNotFoundException。查看此MSDN页面以获取示例和更多信息。

An example of UserNotFoundException

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:

现在,您可以在try ... catch块中包含对此方法的调用,并在catch块中显示MessageBox。例:

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.

当错误对应用程序逻辑不重要时,尽量避免抛出异常(自定义或不自定义),因为异常带有StackTrace和其他一堆数据,它们会影响应用程序执行性能。

#1


0  

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

我没有您的查询文本,但如果它是一个简单的DELETE语句,您可以尝试这样的事情:

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

#2


0  

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

注意:这不是实现此目的的最佳方法,但我只想使用try .. catch ...编写代码,具体提到。没有实际需要尝试...赶上这里

#3


0  

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.

“无法找到用户记录”的情况是逻辑错误。通常,如果找不到某个记录,SqlClient将不会产生异常。所以你无法在一个捕获块中捕获它。

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.

但是,如果无法找到Table,View等对象,或者查询中出现语法错误,SqlClient将产生异常。您可以检查MSDN以查找所有可能的SqlClient异常。

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.

虽然,ExecuteReader()可以执行DELETE查询,但您不需要结果集。这是使用ExecuteNonQuery()的更好方法。此方法返回一个整数,该整数告诉您执行查询所影响的记录数。

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.

要处理“无法找到记录”,您需要实现自己的逻辑。例如,以下代码将删除具有给定ID的记录,如果无法删除则会触发异常。

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.

此外,您可以定义自己的异常,例如UserNotFoundException。查看此MSDN页面以获取示例和更多信息。

An example of UserNotFoundException

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:

现在,您可以在try ... catch块中包含对此方法的调用,并在catch块中显示MessageBox。例:

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.

当错误对应用程序逻辑不重要时,尽量避免抛出异常(自定义或不自定义),因为异常带有StackTrace和其他一堆数据,它们会影响应用程序执行性能。