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

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

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.

Simply check the condition
int a=NewCmd.ExecuteNonQuery();
if(a==0)
//Not updated.
else
//Updated.
ExecuteNonQuery() -> This function return integer value.
Thank you

I know that there is already an answer posted but let`s try something else:
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 will return a bool value

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)
}
})
//this is a nodejs code

Related

How can I execute multiple SQL commands using c#

I was trying to use this code two run two commands in one connection, which I couldn't do, here is my code:
using (SqlConnection connection = new SqlConnection(""))
{
string query = "SELECT DISTINCT quatro, tres FROM todos_cp ORDER BY quatro, tres ";
using (SqlCommand RetriveCommand = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader reader = RetriveCommand.ExecuteReader();
while (reader.Read())
{
string coluna = reader.GetString(reader.GetOrdinal("quatro"));
string coluna1 = reader.GetString(reader.GetOrdinal("tres"));
Boolean ElementDisplayed;
try
{
}
catch (NoSuchElementException i)
{
ElementDisplayed = false;
GDataPicker();
for (int x = 0; x < dataGridView1.Rows.Count; x++)
{
string query2 = #"INSERT INTO table_teste1(Rua, CodigoPostal, Distrito, Concelho, Freguesia, GPS) VALUES(" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";
for (int x = 0; x < dataGridView1.Rows.Count; x++)
{
string query2 = #"INSERT INTO table_teste1 (Rua, CodigoPostal,Distrito,Concelho,Freguesia,GPS ) VALUES (" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";
using(SqlCommand InsertCommand = new SqlCommand(query2,connection))
{
InsertCommand.CommandText = query2;
InsertCommand.ExecuteNonQuery();
}
}
}
}
}
conn.Close();
}
}
My problem is most likely in the lines where I do:
InsertCommand.CommandText = query2;
InsertCommand.ExecuteNonQuery();
And says i already have one datareader.
Help would be really appreciated, thanks in advance!
Append you second command in "query2". As it is inline query Sql will consider that as two different query (Append after semicolon) and will execute in the same connection

Error while running update query for access database

This is my code:
OleDbConnection con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + "/shoping mall.mdb");
con.Open();
OleDbCommand cmd = new OleDbCommand("update RecordofItems set RecordofItems.Bill_no = " + textBox1.Text + ", RecordofItems.Received_from = '" + textBox62.Text + "', RecordofItems.Item_Code = " + textBox2.Text + ", RecordofItems.Quantity = " + textBox32.Text + ", RecordofItems.Sale_Rate = " + textBox47.Text + " where Item_Name = '" + textBox17.Text + "'", con);
int x = 0;
x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("record deleted" + x);
}
else
{
MessageBox.Show("no record exixt");
}
con.Close();
I want to update selected columns in my "RecordofItems" table that has 10 columns but I want to update only 6 selected columns, when I run the query it shows error "no value for one or more required paremeter" What to do ? please help me as soon as you can.
the error No value given for one or more required parameters usually comes when you have misplaced single quote.
try these two.
try assigning your numerical db columns a numerical value viz update your query with these:
RecordofItems.Bill_no = " + Convert.ToInt32(textBox1.Text) + ",
RecordofItems.Item_Code = " + Convert.ToInt32(textBox2.Text) + ",
RecordofItems.Quantity = " + Convert.ToInt32(textBox32.Text) + ",
RecordofItems.Sale_Rate = " + Convert.ToInt32(textBox47.Text) +
or use whatever suitable numerical converter applies to your columns.
one of your text fields might have a single quote in it, so try replacing/updating your text fields like this:
RecordofItems.Received_from = '" + textBox62.Text.Replace("'","''") + "',
so basically, replace single quote with two single quotes.
see if these solve your issue.
Also, do note, never create your sql query by concatenating textboxes(strings). use command parameters. they will save you from sql injection.

Why my query return null

I want to ask why query return null and not update what i want. Sorry I'm still new with asp.net and c#
myquery = "UPDATE kenderaan SET buatan = " + "'" + carmake + "'" + "," +
"model = " + "'" + carmodel + "'" + "," +
"no_enjin = " + "'" + carenjin + "'" + "," +
"cc = " + carcc + "," +
"seatCapacity = " + carseat + "," +
"tahunBuatan = " + caryear + " WHERE no_kenderaan = " + "'" + carid + "'" + "," +
"AND ic = " + "'" + cusid + "'";
connection = new DbConnection();
connection.Update(myquery);
restructure your code into this, use Connection object, Command Object, using statement.
string myquery = "UPDATE kenderaan SET buatan = #carmake ," +
" model = #carmodel ," +
" no_enjin = #carenjin ," +
" cc = #carcc ," +
" seatCapacity = #carseat ," +
" tahunBuatan = #caryear " +
"WHERE no_kenderaan = #carid " +
" AND ic = #cusid ";
using (MySqlConnection _conn = new MySqlConnection("connectionStringHere"))
{
using (MySqlCommand _comm = new MySqlCommand())
{
_comm.Connection = _conn;
_comm.CommandText = myquery;
_comm.CommandType = CommandType.Text;
_comm.Parameters.AddWithValue("#carmake",carmake);
_comm.Parameters.AddWithValue("#carmodel",carmodel);
_comm.Parameters.AddWithValue("#carenjin",carenjin);
_comm.Parameters.AddWithValue("#carcc",carcc);
_comm.Parameters.AddWithValue("#carseat",carseat);
_comm.Parameters.AddWithValue("#caryear",caryear);
_comm.Parameters.AddWithValue("#carid",carid);
_comm.Parameters.AddWithValue("#cusid",cusid);
try
{
_conn.Open();
_comm.ExecuteNonQuery();
MessageBox.Show("Updated!");
}
catch (MySqlException e)
{
MessageBox.Show(e.ToString()); // as mentioned on the comment
}
}
}
Reasons why you need to parameterized your query:
avoids SQL Injection
makes your code more readable
etc.. :D
Sources
AddWithValue
Add (recommended and leaving you this as an assignment :D)
Create a DbCommand to execute the Update statement by using ExecuteNonQuery() method. If you are using SQL Server then you can use this piece of code snippet:
using System.Data.SqlClient;
string query = "UPDATE kenderaan SET buatan = #carmake" +
", model = #carmodel" +
", no_enjin = #carenjin" +
", cc = #carcc" +
", seatCapacity = #carseat" +
", tahunBuatan = #caryear" +
" WHERE no_kenderaan = #carid AND ic = #cusid";
using (SqlConnection conn = new SqlConnection("<connection string>"))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#carmake", carmake);
cmd.Parameters.AddWithValue("#carmodel", carmodel);
cmd.Parameters.AddWithValue("#carenjin", carenjin);
cmd.Parameters.AddWithValue("#carcc", carcc);
cmd.Parameters.AddWithValue("#carseat", carseat);
cmd.Parameters.AddWithValue("#caryear", caryear);
cmd.Parameters.AddWithValue("#carid", carid);
cmd.Parameters.AddWithValue("#cusid", cusid);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try this code in place of your code:
and make sure that varchar parameters are compare to string values.
string myquery = "UPDATE kenderaan SET buatan = '" + carmake + "',model = '"+
carmodel + "',no_enjin = '" +carenjin + "',cc = " + carcc + ",seatCapacity = " +
carseat + ",tahunBuatan = " + caryear +
" WHERE no_kenderaan = '" + carid + "' AND ic = '" + cusid + "'";
connection = new DbConnection();
connection.Update(myquery);
UPDATED: Apologize, I had just corrected your query with your where condition I just removed comma which you used to separate two condition.
To avoid SQL Injection Attacks, Use one of these :
1) Parameters with Stored Procedures
2) Use Parameters with Dynamic SQL
3) Constrain Input
you can find more information over HERE

Update/Insert into table

I have to update table on SQL Server but first i have to check for existing data in table so if data is there update it, if not make a new insert:
cmd_sql.CommandText = " SELECT BrDok as id_dok " +
" FROM ordersstavke " +
" WHERE SifParFil = '" + rw_mat["sifskl_kor"] + "'" +
" AND DokumentTip = '" + rw_mat["vrst_dok"] + "'";
MySqlDataAdapter sql_adapter = new MySqlDataAdapter(cmd_sql);
DataSet dt_dok = new DataSet("DOK_MAT_EXCHANGE");
sql_adapter.Fill(dt_dok);
if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
{
myQuery = " INSERT INTO ordersstavke (BrDok, DocumentTip, SifParFil) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["vrst_dok"] + "', '" +
rw_mat["sifskl_kor"] + "')";
}
else
{
UPDATE DATA
}
But I have an error in the code, the error is here if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
Object reference not set to an instance of an object.
The problem is in this if statement...
DOK_MAT_EXCHANGE is the name of the DataSet, not of the first table.
You should test with
if (dt_dok.Tables[0].Rows.Count == 0)
Also, I think is better to use a syntax like this to discover how many records are presents
cmd_sql.CommandText = "SELECT COUNT(BrDok) as id_dok " +
" FROM ordersstavke " +
" WHERE SifParFil = ?p1 " +
" AND DokumentTip = ?p2";
cmd_sql.Parameters.AddWithValue("?p1", rw_mat["sifskl_kor"] );
cmd_sql.Parameters.AddWithValue("?p2", rw_mat["vrst_dok"] );
int rowCount = (Int32)cmd_sql.ExecuteScalar();
change
DataSet dt_dok = new DataSet("DOK_MAT_EXCHANGE");
to
DataSet dt_dok = new DataSet("ordersstavke ");
and
if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
to
if (dt_dok.Tables["ordersstavke "].Rows.Count == 0)
Accessing the first table via the dataset name is incorrect, that's for setting the XML.
Instead use
dt_dok.Tables[0].Rows.Count;
That being said, you're better off writing this as a single SQL statement instead of a separate select && insert. This way you're not going to the DB multiple times.
var sql = #"if exists(select * from ordersstavke where SifParFil = ? and DokumentTip = ?)
then
-- do insert statement
else
-- do update
end if";
This might also be better done with a stored proc, so you don't have as much SQL code in C#. It's easier to manage multiple operations that way.
And for crying out loud, use SqlParameters, not string concatenation! That's just asking for trouble!
Ok, thanks guys, I wrote it like this
if (ds_dok.Tables[0].Rows.Count <= 0)
{
myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "')";
}
else if (ds_dok.Tables[0].Rows.Count >= 1)
{
myQuery = "UPDATE ordersstavke " +
"SET BrDok = '" + rw_mat["brdok"] + "', " +
"SifParFil = '" + rw_mat["sifskl_kor"] + "', " +
"WHERE BrDok = " + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString() + "'";
}
But there is a small problem in the section update: s_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString(), here it give me that loving error : Object reference not set to an instance of an object.
Maybe the update on MySQL goes on different way, I'm referencing on example on sql server and there update goes differently

SQL c# updating table

I am doing this:
var command = new SqlCommand(query, myConnection);
foreach (DataRow row in dt.Rows)
{
query = #"update FileLog set
FaxStatus=" + "'" + row.ItemArray[0].ToString() + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1].ToString() + "'," +
"dtFaxed=" + "'" + row.ItemArray[2].ToString() + "'," +
"RetryCount=" + "'" + row.ItemArray[4].ToString() + "' " +
"where JobID=" + "'" + row.ItemArray[3].ToString() + "'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
}
JobID is a uniqueidentifier
And I am getting this error:
Conversion failed when converting from a character string to uniqueidentifier.
What am I doing wrong?
The JobID field looks like this:
DB9424E5-1E73-4108-A855-B252E516A2A2
2EB17B8B-C0A1-46FE-82AF-37AEF2A8A6EC
C24F0460-7667-4A3A-8D8F-64B9728C2359
8DCDB020-8C7B-493E-9D21-719CBAFC16B6
This will be more secure (safe from SQL-injection), easer to read and understand, and faster because prepared statements get their execution plan cached. If you have different sql, it can't use a cached execution plan.
SqlCommand cmd =
new SqlCommand(
#"update FileLog set FaxStatus=#fs, FaxedPageCount=#ct, #dtFaxed=#dt, ......., where JobID=#id")
{CommandType = CommandType.Text};
cmd.Prepare();
cmd.Connection = connection;
cmd.Parameters["#id"].Value = row.ItemArray[0];
...
i found the solution. turns out you need to do this:
var command = new SqlCommand(query, myConnection);
foreach (DataRow row in dt.Rows)
{
query = #"update FileLog set
FaxStatus=" + "'" + row.ItemArray[0].ToString() + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1].ToString() + "'," +
"dtFaxed=" + "'" + row.ItemArray[2].ToString() + "'," +
"BiscomCode=" + "'" + row.ItemArray[5].ToString() + "', " +
"RetryCount=" + "'" + row.ItemArray[4].ToString() + "' " +
"where CONVERT(VARCHAR(255), JobID) =" + "'" + row.ItemArray[3].ToString() + "'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
}
you have to convert it to a varchar first
It's very likely one of your job ids is not a valid Guid.
Here's a method to check for guid:
public static bool IsGuid(string input)
{
Regex isGuid = new Regex(#"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
try
{
return isGuid.IsMatch(input);
}
catch
{
return false;
}
}
So before issuing the query command do a check on the jobid. If it doesn't match, escape it and log it to revisit later.

Categories

Resources