c# - 如何使用C#检查SQL查询是否成功

标签 c# sql sql-server

我是 C# 和 SQL 的新手。现在我从一个表单访问一个类中的函数。

我的代码是

public void updateSupplierInformation(string id, string name, string balance, string place, string address, string phone, string bankname, string bankbranch, string accountno)
{
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }

        SqlCommand NewCmd = conn.CreateCommand();
        NewCmd.Connection = conn;
        NewCmd.CommandType = CommandType.Text;
        NewCmd.CommandText = " update supplier set " + " ID = " + "'" + id + "'" + " , NAME = " + "'" + name + "'" + " , BALANCE = " + "'" + balance + "'" + " , PLACE = " + "'" + place + "'" + "  , LOCATION = " + "'" + address + "'" + ",  PHONE = " + "'" + phone + "'" + " , BANK_NAME = " + "'" + bankname + "'" + " , BANK_BRANCH = " + "'" + bankbranch + "'" + ", ACCOUNT_NO = " + "'" + accountno + "'" + " where ID = " + "@id";
        NewCmd.Parameters.AddWithValue("@id",id);
        NewCmd.ExecuteNonQuery(); 
        conn.Close();
    }

现在,如果数据库中不存在具有给定 id 的记录,应用程序会立即停止。我该如何处理?我想显示一条消息,表明输入的数据有误,并要求用户输入其他数据

最佳答案

ExecuteNonQuery() 返回受 INSERT、UPDATE 或 DELETE 语句影响的行数。如果需要检查 sql 异常,则必须在函数中包含 try catch 语句。

public void updateSupplierInformation(string id, string name, string balance, string place, string address, string phone, string bankname, string bankbranch, string accountno)
    {
       try
       {
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }

        SqlCommand NewCmd = conn.CreateCommand();
        NewCmd.Connection = conn;
        NewCmd.CommandType = CommandType.Text;
        NewCmd.CommandText = " update supplier set " + " ID = " + "'" + id + "'" + " , NAME = " + "'" + name + "'" + " , BALANCE = " + "'" + balance + "'" + " , PLACE = " + "'" + place + "'" + "  , LOCATION = " + "'" + address + "'" + ",  PHONE = " + "'" + phone + "'" + " , BANK_NAME = " + "'" + bankname + "'" + " , BANK_BRANCH = " + "'" + bankbranch + "'" + ", ACCOUNT_NO = " + "'" + accountno + "'" + " where ID = " + "@id";
        NewCmd.Parameters.AddWithValue("@id",id);
        int a=NewCmd.ExecuteNonQuery(); 
        conn.Close();
        if(a==0)
          //Not updated.
        else
          //Updated.
        }
        catch(Exception ex)
         {
         // Not updated
         }
    }

关于c# - 如何使用C#检查SQL查询是否成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14293179/

相关文章:

c# - Twilio 休息 API 错误代码 21612

c# - 模拟 DbContext.set<T>.Add() EF6

sql - SQL 选择查询中的排序结果

sql - 查找数据库中某一列有 2 个或多个相同值的行

c# - 如何执行参数化 SQL 查询(使用带@变量的 LIKE)

c# - 如何为表单设置 "preferred size"?

c# - UnityEngine.WWW.WWW(string, byte[], System.Collections.Hashtable)' 已过时

sql - 从sql查询中的列中获取多次出现的字符串

php - 我们如何在 mysql 中使用 JOIN 设置计数

mysql - 特定条件匹配后分组