Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

sql

sql-server

I am new to C# and SQL. Now from a form I access a function in a class.

My code is

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();
    }

Now if a record doesn't exist in the database with the given id the application stops immediately. How can I handle this? I want to show a message that the data entered is wrong and ask the user to enter another data

like image 527
Aravind Bharathy Avatar asked Jan 12 '13 12:01

Aravind Bharathy


People also ask

How do you validate a selected query is successful?

Checking if select was "successful" (by the way what is it? any select will be successful if there are appropriate columns in table) but returning 1 instead of selected values looks meaningless... If by successful you mean successful execution, then a try-catch block is all you need.

How can I tell if insert is successful C#?

If you're going to do that, then I'd simply have my function return a Boolean to simply tell me if the insert was successful or not. return myCommand. ExecuteNonQuery(). Equals(1);

How do I know if SQL Server update query was successful?

You can use @@ROWCOUNT to get the number of rows affected by the last query. This can be used to decide whether your WHERE clause actually matched something, for example. Show activity on this post. You can use the return value of the ExecuteNonQuery to check if the update was successful or not.


1 Answers

Simply check the condition

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

ExecuteNonQuery() -> This function return integer value.

Thank you

like image 118
Dilip Kumar Choudhary Avatar answered Oct 06 '22 01:10

Dilip Kumar Choudhary