This question already has answers here:
SQL update statement in C#
(10 answers)
Closed 5 years ago.
enter image description here
I am trying to update data in a SQL Server table. I get a message that data is saved, after a query execution.
But when I check in that table, I find that the data is not saved. Is anything wrong in my query?
I am using SQL Server 2008 and C# for coding.
SqlCommand cmd1 = new SqlCommand("UPDATE Inward_Rpt SET Date='" + date + "',Cashier_Name='" + cashier_name + "',Supplier_Code='" + sup_code + "',Supplier_Name='" + name + "',Payment_Mode ='" + p_method + "',Total_Bill='" + tot_bill + "',Total_Paid='" + tot_paid + "',Previous_Due = '" + total_due + "',Current_Due ='" + c_due + "',Remark ='" + remark + "'WHERE Supplier_Name='" + name + "'", con);
cmd1.ExecuteNonQuery();
MessageBox.Show("Data Saved..");
I think I found your error. Your WHERE clause is using the same name that you are updating the Supplier Name to. Assuming this is a new name, you will never find the record you want to update. The below code is cleaner, not prone to injection issues, and it should work the way you want.
Note that you will have to provide a new variable to cater to the name / sup_name situation.
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd1.CommandText = #"
UPDATE Inward_Rpt
SET Date = #date
, Cashier_Name = #cashier_name
, Supplier_Code = #sup_code
, Supplier_Name = #sup_name
, Payment_Mode = #p_method
, Total_Bill = #tot_bill
, Total_Paid = #tot_paid
, Previous_Due #total_due
, Current_Due = #c_due
, Remark = #remark
WHERE Supplier_Name = #name";
cmd1.Parameters.AddWithValue("#date", date);
cmd1.Parameters.AddWithValue("#cashier_name", cashier_name);
cmd1.Parameters.AddWithValue("#sup_code", sup_code);
cmd1.Parameters.AddWithValue("#sup_name", sup_name);
cmd1.Parameters.AddWithValue("#p_method", p_method);
cmd1.Parameters.AddWithValue("#tot_bill", tot_bill_name);
cmd1.Parameters.AddWithValue("#tot_paid", tot_paid);
cmd1.Parameters.AddWithValue("#total_due", total_due);
cmd1.Parameters.AddWithValue("#c_due", c_due);
cmd1.Parameters.AddWithValue("#remark", remark);
cmd1.Parameters.AddWithValue("#name", name);
cmd1.ExecuteNonQuery();
MessageBox.Show("Data Saved..");
Is the All the Fields are String Datatype in your Database Table? Check the Datatypes Because u give Single Quotes for all Data. If the Table Datatype is Number Remove the Single Quotes.
SqlCommand cmd1 = new SqlCommand("UPDATE Inward_Rpt SET Date='" + date + "',Cashier_Name='" + cashier_name + "',Supplier_Code=" + sup_code + ",Supplier_Name='" + name + "',Payment_Mode ='" + p_method + "',Total_Bill='" + tot_bill + "',Total_Paid='" + tot_paid + "',Previous_Due = '" + total_due + "',Current_Due ='" + c_due + "',Remark ='" + remark + "'WHERE Supplier_Name='" + name + "'", con);
Related
I'm building simple library application. I'm using C# and SQL Server 2017.
While running a function to check if the book already exists I'm getting an error near "Name".
public bool DoesItExist()
{
mainSet mset = new mainSet();
string query = "SELECT * FROM [Library].[dbo].[ViewBook] WHERE " +
"Title = '" + this.title + "' AND " +
"DateOfFirstRelease = " + this.release_date + " AND " +
"Name = '" + this.author_name + "' AND " +
"2Name= '" + this.author_2name + "' AND " +
"Surname = '" + this.author_surname + "' AND " +
"Category = '" + this.category + "' AND " +
"Publishing = '" + this.Publishing+ "' ";
SqlConnection cnn = new SqlConnection(mset.dataBaseConect);
SqlCommand cmd = new SqlCommand(query, cnn);
cnn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows) return true;
else return false;
}
All "this." are are parameters in "Title" class.
All parameters are type:string except "DateOfRelease" which is type:int
[ViewBook] is a view in [Library] database.
Error I'm getting:
System.Data.SqlClient.SqlException:
An expression of non-boolean type specified in a context where a condition is expected, near 'Name'.”
Example of the cmd query:
"SELECT * FROM [Library].[dbo].[ViewBook] WHERE Title = 'Book Name' AND DateOfFirstRelease = 2004 AND Name = 'George' AND 2Name= '' AND Surname = 'Martin' AND Category = 'Economy' AND Publishing = 'PublishingTest' "
There is a big caveat with this answer; I'm not a c# coder so I have not tested this. I very rarely go near C#, and only when I do it's because I'm assisting our developers at work with their SQL Server requirements (as I'm a DBA/SQL Developer). What did I do though? I used the documentation (SqlCommand.Parameters Property & SqlDbType Enum) to write a properly parametrised query which should work (I added a comment as to why I believe your query failed as well):
string query = "SELECT * FROM Library.dbo.ViewBook" +
" WHERE Title = #Title" +
" AND DateOfFirstRelease = #ReleaseDate" +
" AND [Name] = #AuthorName" + //Name is a keyword, so I prefer to quote it
" AND [2Name] = #AuthorName2" + //Quoted as a column that begins with a number needs to be delimit identified
" AND Surname = #Surname" +
" AND Category = #Category" +
" AND Publishing = #Publishing;";
using (SqlConnection cnn = new SqlConnection(mset.dataBaseConect))
{
SqlCommand cmd = new SqlCommand(query, cnn);
cmd.Parameters.Add("#Title",SqlDbType,VarChar,50); //Guessed datatype
cmd.Parameters["#Title"].Value = this.title;
cmd.Parameters.Add("#ReleaseDate",SqlDbType.Date); //Guessed datatype
cmd.Parameters["#ReleaseDate"].Value = this.release_date;
cmd.Parameters.Add("#AuthorName",SqlDbType.VarChar,50); //Guessed datatype
cmd.Parameters["#AuthorName"].Value = this.author_name;
cmd.Parameters.Add("#AuthorName2",SqlDbType.VarChar,50); //Guessed datatype
cmd.Parameters["#AuthorName2"].Value = this.author_2name;
cmd.Parameters.Add("#Surname",SqlDbType.VarChar,50); //Guessed datatype
cmd.Parameters["#Surname"].Value = this.author_surname;
cmd.Parameters.Add("#Category",SqlDbType.VarChar,50); //Guessed datatype
cmd.Parameters["#Category"].Value = this.category;
cmd.Parameters.Add("#Publishing",SqlDbType.VarChar,50); //Guessed datatype
cmd.Parameters["#Publishing"].Value = this.Publishing;
cnn.Open();
SqlDataReader reader = cmd.ExecuteReader();
}
Trying to update records in my datatable using textboxes on a button click. The error message says is cannot insert a duplicate value, and shows the value that I have entered into txtID. This is the code for the update button:
private void btnUpdate_Click(object sender, EventArgs e)
{
connection.Open();
SqlCommand command = new SqlCommand();
String query = "UPDATE Bug SET Tester_ID=" + txtID.Text + "',Tester_Name= '" + txtName.Text + "',Application_Name= '" + txtApp.Text + "',Class_Name= '" + txtClass.Text + "',Line_No= '" + txtLineNo.Text + "',Error_Description= '" + txtDesc.Text + "',Source_Code= '" + txtSource.Text + "',Status= '" + txtStatus.Text + "')";
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
adapter.SelectCommand.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Data Updated Successfully");
}
You do not have where clause in that query, so it is updating all records in the table, which is making some records duplicate. Hence the error.
The could be due to your defined table structure.
P.S. You should look for SQL injection attack and should parameterize your query to avoid it.
Edit based on your comment
String query = "UPDATE Bug Set Tester_Name= '" + txtName.Text + "',Application_Name= '" + txtApp.Text + "',Class_Name= '" + txtClass.Text + "',Line_No= '" + txtLineNo.Text + "',Error_Description= '" + txtDesc.Text + "',Source_Code= '" + txtSource.Text + "',Status= '" + txtStatus.Text + "' WHERE Tester_ID='" + txtID.Text + "'";
If Tester_Id is numeric, you don't need those quotes.
Where clause comes after Set.
Here is the Parameterized version:
String query = "UPDATE Bug Set Tester_Name=#Tester_Name,Application_Name= #AppName,Class_Name= #Class_Name,Line_No= #Line_No,Error_Description= #Error_Description,Source_Code= #Source_Code,Status= #Status WHERE Tester_ID=#Tester_ID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#Tester_Name", "XYZ");
// other params
command.Parameters.AddWithValue("#Tester_ID", 10);
String strSql = "insert into BaseData (Item," + dataGridView1.Columns[3].Name + "," + dataGridView1.Columns[4].Name + ") values ('" + row.Cells[0].Value + "','" + row.Cells[3].Value + "','" + row.Cells[4].Value + "')";
objCmd = new OleDbCommand(strSql, lConn);
objCmd.ExecuteNonQuery();
strSql = "select id from BaseData where Item = '" + row.Cells[0].Value + "' and " + dataGridView1.Columns[1].Name + " = '" + row.Cells[3].Value + "' And " + dataGridView1.Columns[2].Name + " = '" + row.Cells[4].Value + "'";
OleDbCommand command = new OleDbCommand(strSql, lConn);
OleDbDataReader reader = command.ExecuteReader();
String id = "";
while (reader.Read())
{
id = reader.GetString(0);
}
reader.Close();
strSql = "insert into tranjaction (Base_id,quentity,price,other) values ('" + id + "' , ' " + row.Cells[2].Value + "','" + row.Cells[1].Value + "')";
objCmd = new OleDbCommand(strSql, lConn);
objCmd.ExecuteNonQuery();
When I run this, Microsoft Visual Studio Error occur on Line 10. (ExecuteReader)
The Error is here.
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: No value given for one or more required
parameters.
How could I fix this error?.
Either your field names are wrong (quentity?) or it's because you have unbalanced fields to parameters. You are inserting into 4 fields, but you are only supplying 3 values. Use parameters instead, it would make your life easier.
Try changing it to this:
strSql = "insert into tranjaction (Base_id,quentity,price,other) values (#id , #quentity, #price, #other)";
using (OleDbCommand cmd = new OleDbCommand(sqlSql, IConn)) {
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#quentity", row.Cells[2].Value);
cmd.Parameters.AddWithValue("#price", row.Cells[1].Value);
cmd.Parameters.AddWithValue("#other", other); // <- missing
cmd.ExecuteNonQuery();
}
When I've received this error in the past it has always been because of a simple typo. Like the others have mentioned it looks like you spelled "quantity" wrong which could be part of the problem.
In this line
strSql = "insert into tranjaction (Base_id,quentity,price,other) values ('" + id + "' , ' " + row.Cells[2].Value + "','" + row.Cells[1].Value + "')";
you are inserting 4 values (Base_id,quentity,price,other), but you are only inserting 3 values (id, row.Cells[2].Value, row.Cells[1].Value). Giving a value for other should fix the problem.
Another thing that would cause this error, which is probably your situation, is if you've spelled one of the column names incorrectly. And since you are using column names from your datagridview, and some of your written column names seem mis-spelled, you should double check the spelling in your query strings.
I have an error that I can't fix ... I really don't know why .
I'm using this code tu upload a file in my database, i want to use the BLOB now .
if (FileUpload1.HasFile)
try
{
//FileUpload1.SaveAs("C:\\inetpub\\wwwroot\\ClientPortalCs\\"
//+ GetTheCurrentDirectory(MyTreeView.SelectedNode)
//+ "\\" + FileUpload1.FileName);
//LabelFile.Text = "File name: " +
//FileUpload1.PostedFile.FileName + "<br>" +
//FileUpload1.PostedFile.ContentLength + " kb<br>" +
//"Content type: " + FileUpload1.PostedFile.ContentType;
dbConnection.Open();
dynamic queryString = ("INSERT INTO Files (Name,Path,UserUpload,Date,Data) VALUES ('"
+ FileUpload1.FileName + "','" + GetTheCurrentDirectory(MyTreeView.SelectedNode) + "','" + Request.Cookies["UserSettings"]["UserName"] + "','" + DateTime.Now + "','" + FileUpload1.FileBytes + "' );"
+ "SELECT CAST(scope_identity() AS int)");
SqlCommand theCommand1 = new SqlCommand(queryString, dbConnection);
int newFid = (Int32)theCommand1.ExecuteScalar();
dynamic queryStringFolder = ("INSERT INTO FILES_FOLDERS (Folder_Id,File_Id) VALUES ('"
+ MyTreeView.SelectedValue + "'," + "'" + newFid + "')");
theCommand1 = new SqlCommand(queryStringFolder, dbConnection);
theCommand1.ExecuteNonQuery();
dbConnection.Close();
}
In my database the field DATA in the table files is a varbinary(max) .
The parameter for DATA field in the query is the bytes of the file I try to upload .
The error occured is :
"Error Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. "
Can someone tell me why ?
Thank you very much .
The problem, I think, is that you are passing in the byte [] of your image as a string because you are enclosing it in single quotes.
Remove the single quotes around here:
'" + FileUpload1.FileBytes + "'"
One more recommendation: Use parameters for your queries. You'll save yourself from sql injection attacks, your queries may run faster and you'll eliminate this kind of mistakes in the future.
UPDATE - using parameters:
string queryString = "INSERT INTO Files (Name,Path,UserUpload,Date,Data) VALUES (#Name,#Path,#UserUpload,#Date,#Data)";
SqlCommand theCommand1 = new SqlCommand(queryString, dbConnection);
theCommand1.Parameters.AddWithValue("#Name",FileUpload1.FileName);
theCommand1.Parameters.AddWithValue("#Path",GetTheCurrentDirectory(MyTreeView.SelectedNode));
theCommand1.Parameters.AddWithValue("#UserUpload",Request.Cookies["UserSettings"]["UserName"]);
theCommand1.Parameters.AddWithValue("#Data",FileUpload1.FileBytes);
theCommand1.Parameters.AddWithValue("#Date",DateTime.Now);
int newFid = (Int32)theCommand1.ExecuteScalar();
So, I have been trying to fix this for about two months. It all started when my "dev" machine went kaput and I set it up on my laptop. It was working fun on my old PC but, it does not work on my new PC and never did on laptop.
I structured the SQL Server as much like the first one as I could remember but, it started giving me SQLExceptions. I googled it, I searched on here for it, I tried different solutions. Nothing.
I will post the offending code and I am hoping someone will be able to help me see my flaw. I am sure it is something stupid.
SqlCommand sc = sqlc.CreateCommand();
sc.CommandText = "SELECT pNumber FROM database WHERE pNumber = '" + Number.ToString() + "'";
SqlDataReader sdr = sc.ExecuteReader();
if (sdr.Read().ToString() != null)
{
sdr.Close();
sc.CommandText = "UPDATE word SET word = '" + Word + "' WHERE pNumber = '" + Number.ToString() + "'";
HERE IS WHERE THE ERROR OCCURS----> sc.ExecuteReader();
}
else
{
sdr.Close();
sc.CommandText = "INSERT INTO database VALUES(" + Number.ToString() + ",'" + Word + "',0, 0, 0)";
sc.ExecuteNonQuery();
sc.CommandText = "SELECT * FROM database WHERE pNumber = '" + Number.ToString() + "'";
SqlDataReader dataRead = sc.ExecuteReader();
for (int x = 0; x < 6; ++x)
{
User[x] = dataRead.GetString(x);
}
}
sqlc.Close();
EDIT: SqlException: Invalid object name: 'word'.
at System.Data.SqlClient.SqlConnection.OnError(...
Change your input values to parameters. It's much safer, and might fix your issue if it's a problem caused by accidental SQL injection.
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx
Like this:
sc.CommandText = "INSERT INTO database VALUES(#number,#word,0, 0, 0)";
sc.Parameters.Add("#number", SqlType.Int).Value = number;
sc.Parameters.Add("#word", SqlType.Int).Value = Word
sc.CommandText = "UPDATE word SET word = '" + Word + "' WHERE pNumber = '" + Number.ToString() + "'";
should probably read
sc.CommandText = "UPDATE database SET word = '" + Word + "' WHERE pNumber = '" + Number.ToString() + "'";
I changed the tablename in the SQL query, that is all.
Where your code reads
sc.CommandText = "SELECT pNumber FROM database WHERE pNumber = '" + Number.ToString() + "'";
does that mean your user-defined database is actually named "database"? The word "database" is a reserved word, and this could be causing you grief.