How to check whether a SQL query is successful with C#

ExecuteNonQuery() returns number of rows affected by an INSERT, UPDATE or DELETE statement.If you need to check sql exception you have to include a try catch statement in your function.

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

ExecuteNonQuery returns the number of rows affected - if it's 0, that means there were no matching rows to update. Of course, that's only if the update actually "works" in terms of not throwing an exception... whereas I suspect it's throwing an exception in your case, which probably isn't to do with the row not existing in the database. (It's possible that there's some code you haven't shown which does depend on the row existing, mind you.)

Additionally:

  • You should use parameterized SQL for all parameters rather than including the values directly in your SQL.
  • You should use using statements to dispose of resources reliably.
  • It looks like you're using a single connection - don't do that. Create (and dispose via using) a new connection each time you want to perform a database operation, and let the connection pool handle the efficiency
  • Work out why the application is just stopping. An exception is almost certainly being thrown, and it's really important that when that happens, you get the details of the exception. You may want to catch it and keep going (at some high level) depending on the exact context... but you should always at least end up logging it.

My guess (on a casual inspection) is that the problem is that your update statement tries to update the ID, which would presumably be read-only. But you'll find that out when you fix your exception handling.

Tags:

C#

Sql

Sql Server