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
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.
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);
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.
Simply check the condition
int a=NewCmd.ExecuteNonQuery();
if(a==0)
//Not updated.
else
//Updated.
ExecuteNonQuery() -> This function return integer value.
Thank you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With