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

问题描述 投票:0回答:5

我是 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
的记录,应用程序将立即停止。我该如何处理这个问题?我想显示一条消息,表明输入的数据错误并要求用户输入另一个数据

c# sql sql-server
5个回答
29
投票

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

22
投票

ExecuteNonQuery
返回受影响的行数 - 如果为 0,则意味着没有要更新的匹配行。当然,只有当更新实际上“有效”而不抛出异常时...而我怀疑它在您的情况下抛出异常,这可能与数据库中不存在的行有关。 (请注意,您可能没有显示某些代码,这些代码确实取决于现有的行。) 另外:

您应该对
    所有
  • 参数使用参数化 SQL,而不是直接在 SQL 中包含值。 您应该使用
  • using
  • 语句来可靠地处置资源。
    看起来您正在使用单个连接 - 不要这样做。每次要执行数据库操作时创建(并通过
  • using
  • 处置)一个新连接,并让连接池处理效率
    找出应用程序刚刚停止的原因。几乎肯定会引发异常,并且当发生这种情况时,获取异常的详细信息非常重要。您
  • 可能
  • 想要抓住它并继续(在较高级别)取决于确切的上下文......但您应该始终至少最终记录它。
  • 我的
猜测

(偶然检查)是问题是你的更新语句试图更新ID,这可能是只读的。但当你修复异常处理时你就会发现这一点。


2
投票

int a=NewCmd.ExecuteNonQuery(); if(a==0) //Not updated. else //Updated.

ExecuteNonQuery() -> 该函数返回整数值。

谢谢你


1
投票

SqlConnection SQLConn = new SqlConnection("datahere"); SqlCommand SQLComm = new SqlCommand(); SQLcomm.Connection = SQLConn; SQLConn.Open(); SQLComm.CommandText = "SQL statement goes here" SqlDataReader dataReader = SQLComm.ExecuteReader(); dataReader.Read(); if(dataReader.HasRows == true){ //if it has rows do code //do code } else{ // do other code }

HasRows 将返回一个布尔值 


-1
投票

let sql = `UPDATE TABLE SET column = '${data}' WHERE column = "value` db.query(sql, (err, result)=> { console.log(result.affectedRows); if(err) { console.log(err); return res.send({ message: "Error occured. please retry", }); } else if(result.affectedRows != 0) { console.log(result) return res.send({ success:true, message: "updated!" }); }else if(result.affectedRows == 0) { console.log(result) return res.send({ success:false, message: "not updated!" }); } else { console.log(result) } })

© www.soinside.com 2019 - 2024. All rights reserved.