Update in SQL query doesn't work c# - c#

I want to update data in my SQL Server table, this code here works fine in my other project but when I copied it to other project it doesn't work anymore.
Here's my code:
con.Open();
float prc = float.Parse(textBox4.Text);
int sum = int.Parse(textBox3.Text);
string sql = "UPDATE LIB_INVENTORY set PRICE=(" + prc + "), QUANTITY=([QUANTITY]) +
(" + sum + "), BSTATUS='" + textBox5.Text + "' where BOOKNAME='"
+ textBox1.Text + "' and PUBLISHER='" + textBox2.Text + "'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("One item updated updated!");
It runs successfully but when I checked the table no data has been successfully updated. I checked my code but it is really the same as my other project that works fine. Can somebody help me?

if no error is there then it means where clause is not fulfilling. i think your has typed like :
where BOOKNAME='"<spaace>+ textBox1.Text+<spaace>"' and PUBLISHER='"<spaace>+ textBox2.Text +<spaace>"'";
so just erase space and
try this out.
string sql = "UPDATE LIB_INVENTORY set PRICE=("+prc+"), QUANTITY= ([QUANTITY]) + ("+sum+"), BSTATUS='"+textBox5.Text+"' where BOOKNAME='"+textBox1.Text+"' and PUBLISHER='"+textBox2.Text+"'";

as suggested you should really use parameters for your sql query. On top of this do the following :
SqlCommand cmd = new SqlCommand(sql, con);
int nbrUpdates = cmd.ExecuteNonQuery();
con.Close();
if (nbrUpdates>0) MessageBox.Show("One item updated updated!");
else MessageBox.Show(sql);
You can then check if the string in the sql is correct.
Also log in to your database manually and check if the data you want to update is in fact there.
If it is and the update still does not work, make your code do a select statement for the data you want to update. You still might be accessing the wrong database.
Now to start using sql with parameters like you are supposed to read this :
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'where'.' ||||who can help me with this error?

the code is below and the error starting from sqlCommand cmd the 13th line of this code
private void button2_Click(object sender, EventArgs e)
{
if (StudenUsn.Text == "" )
{
MessageBox.Show("Enter The Student Number");
} else {
Con.Open();
String query = "update Student_tbl set StdName='" + StudName.Text + "',where FatherName='" + FtName.Text + "',where MotherName='" + MtName.Text + "',where StdAddress='" + Address.Text + "',where Collage ='" + Collage.Text + "'set StdRoom = " + StRmNum.SelectedValue.ToString()+",StdStatus = '"+ StudSt.SelectedItem.ToString() + "' where StdUsn ='"+StudenUsn+ "')";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
MessageBox.Show("Room Successfully Updates");
Con.Close();
FillStudentDGV();
}
}
Your code should look more like:
private void button2_Click(object sender, EventArgs e)
{
if (StudenUsn.Text == "" )
{
MessageBox.Show("Enter The Student Number");
} else {
var query = #"
update Student_tbl
set
StdName=#sn,
FatherName=#fn,
MotherName=#mn,
StdAddress=#sa,
Collage=#c,
StdRoom=#sr,
StdStatus=#ss
where
StdUsn=#su";
using var con = new SqlConnection(YOUR_CONN_STR_HERE);
using var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue(#sn, StudName.Text);
cmd.Parameters.AddWithValue(#fn, FtName.Text);
cmd.Parameters.AddWithValue(#mn, MtName.Text);
cmd.Parameters.AddWithValue(#sa, Address.Text);
cmd.Parameters.AddWithValue(#c, Collage.Text);
cmd.Parameters.AddWithValue(#sr, StRmNum.SelectedValue);
cmd.Parameters.AddWithValue(#ss, StudSt.SelectedItem);
cmd.Parameters.AddWithValue(#su, StudenUsn);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Room Successfully Updates");
FillStudentDGV();
}
}
There are good reasons to avoid using AddWithValue if you use SQLServer which you can get into at a later date if you want, but it's convenient for me (who doesn't know the types and widths of your columns) dealing with the current massive elephant in the room which is your SQL is massively vulnerable to a hacking technique known as sql injection (and to a lesser extent it would blow up with an error for any student whose name included an apostrophe) - using AddWithValue might make your query slightly slower, but better that than it be the cause of the next data breach; learn how to write SQLs right, right now
Never ever take data supplied by a user and concatenate it into an SQL string. Doing so essentially, in most cases, gives the user access to your database. So many big companies whose developers should know better, put up expensive firewalls and security and then let anyone in via this back door anyway; sql injection prone systems are one of the leading causes of hacks in the world today
Always use #parameter placeholders in the SQL for user data and add a parameter to the command's parameters collection, containing the data
Now on the topic of your actual error; the pattern for an update is
update table
set col1=#param1, col2=#param2 ...
where (some conditions)
You have one where and one set. If there is some conditional aspect to your set, like you only want to update the student name/address if it is currently null then you can do like:
update table
set
name=case when name is null then #n else name end,
address=case when address is null then #a else address end
where (some conditions)
Or more simply
update table
set
name=coalesce(name, #n)
address=coalesce(address, #a)
where (some conditions)
You can't mix n match and say "where this=that where this2=that2 set this3=that3" - that's a syntax error. Where is for picking the row you want to update and set is for starting a block of commas separated columns and values the row data is to be updated to.
Strive to write your sql nicely formatted inside an #string; it's a programming language all of its own, and will be easier to debug if it's laid out nicely
Can u try with it ?
String query = "update Student_tbl set StdName='" + StudName.Text + "',StdRoom = '" + StRmNum.SelectedValue.ToString()+"',StdStatus = '"+ StudSt.SelectedItem.ToString() + "' where FatherName='" + FtName.Text + "' and MotherName='" + MtName.Text + "' and StdAddress='" + Address.Text + "' and Collage ='" + Collage.Text + "' and StdUsn ='"+StudenUsn+ "'";

insert into ms access database

I use the following code to insert a record from one database to another but it doesn't work. I tried the query in MS-ACCESS 2007 and it works fine but it doesn't work when called programmatically from my C# code?
string query_insert = "INSERT INTO Questionnaires_Table(BranchName,Factor,Region,Branch_ID,Current_Date,No_Employees) "
+ "SELECT BranchName,Factor,Region,Branch_ID,Current_Date,No_Employees "
+ "FROM Questionnaires_Table IN '" + dialog.FileName + "' Where Branch_ID = " + textBox1.Text ;
dbConnDest.Open();
OleDbDataAdapter dAdapter = new OleDbDataAdapter();
OleDbCommand cmd_insert = new OleDbCommand(query_insert, dbConnDest);
dAdapter.InsertCommand = cmd_insert;
textBox2.Text = query_insert.ToString();
dbConnDest.Close();
When I take the the content of query_insert in ms access, it works fine.
I think you need to use
cmd_insert.executeNonQuery()
Remove the comma after the last field name in the SELECT list.
"SELECT BranchName,Factor,Region,Branch_ID,Current_Date,No_Employees"
dAdapter.Update();
should do the trick
This seems suspect:
" Where Branch_ID = " + textBox1.Text ;
Does textBox1 contain a numeric ID? Does the ID that is entered exist in the source database?
I would 1) do a check that the ID exists and warn the user if it doesn't, and 2) change the query to use paramters instead of concatenating SQL.
What would happen if your company opened a branch with the ID of
"1; DROP TABLE Branches"

I am getting error while inserting to SQL

datetime=Datetime.Now;
string strquery = #"INSERT INT0 [Destination_CMS].[dbo].[Destination_CMS_User]
values('" + userid + "','" + email + "','"
+ userType + "','" + userStatus + "','" + processed + "','"
+ datetime.ToLongDateString() + "')";
cmd = new SqlCommand(strquery, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
I am getting error:
Incorrect syntax near 'Destination_CMS'.
You've written INT0 rather than INTO.
Also, use parameterized queries.
You should try to change INT0 to INTO.
INSERT INT0 [Destination_CMS].[dbo]
I think its INSERT INTO rather than INT0 (zero)
Print the query to the screen, and verify where the syntax error is.
Next to that; use parametrized queries, like this:
string query = "INSERT INTO [tablename] ( column, column ) VALUES (#p_param1, #p_param2)";
var command = new SqlCommand (query);
command.Parameters.Add ("#p_param1", SqlDbType.DateTime).Value = DateTime.Now;
...
You are risking sql injection, if not using parametrized queries..
Your problem looks solved, so my next question would be, why not use an ORM like NHibernate/EF etc.., depending on your requirements offocourse, but ADO.NET plumbing in my books is where performance is an absolute issue.
You could write this as a stored procedure instead, which has the advantage of making typos like this a lot easier to spot and fix.

SQL Delete query not working properly

I had a logic error in my sql delete query which would not give any error in visual studio and did not delete the record in the database
Here is a snippet of my code
SqlCommand cmd = new SqlCommand(
#"DELETE FROM table_name
WHERE item_id=" + itmIDs +
" AND vendor_id=" + vendIDs +
" AND dozen=" + selectedItmDzn +
" AND quantity=" + selectedItmQty +
" AND total_price=" + selectedItmTotPrc + "",
con);
cmd.ExecuteNonQuery();
here is my conString
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=InvenotyBB;Integrated Security=SSPI")
I have confirmed that the other verbs (select, update, etc) work, just not the specific command for delete.
I can almost guarantee your connection string has:
User Instance=true;AttachDbFileName=|Data Directory|...something.mdf;
If this is the case, STOP DOING THAT. The AttachDbFileName feature actually creates a copy of your database file. So the one you have open in Management Studio or Visual Studio is different from the one your application created via the connection string. Your application deletes from the copy, there are no exceptions (because it worked), you refresh the original, and it looks like it didn't work.
See the answer from #marc_s's here:
https://stackoverflow.com/a/7222952/61305
If this isn't it, then I suspect either (a) errors are being ignored due to try/catch somewhere, or (b) your method for checking if the command worked is suspect. For example, if you are relying on a count, and the where clause matches zero rows, then the command worked but it didn't delete anything, therefore the count remains the same.
If neither of those are true, then goto line 1 of my answer. There is no magic here, a delete command will either affect 0 or more rows, or it will return an exception. Anything else can only be explained by improper troubleshooting / debugging.
Given this original code (via my formatting):
SqlCommand cmd = new SqlCommand(
#"DELETE FROM table_name
WHERE item_id=" + itmIDs +
" AND vendor_id=" + vendIDs +
" AND dozen=" + selectedItmDzn +
" AND quantity=" + selectedItmQty +
" AND total_price=" + selectedItmTotPrc + "",
con);
cmd.ExecuteNonQuery();
Let's change this to:
string deleteQuery =
#"DELETE FROM table_name
WHERE item_id=" + itmIDs +
" AND vendor_id=" + vendIDs +
" AND dozen=" + selectedItmDzn +
" AND quantity=" + selectedItmQty +
" AND total_price=" + selectedItmTotPrc + "";
SqlCommand cmd = new SqlCommand(deleteQuery, con); /* set a breakpoint here */
cmd.ExecuteNonQuery();
Set the breakpoint and copy-paste that query to a comment here so we can see it.

asp.net SQL Server insert statement tidyup + error

I have a form which inserts data into a database.
There are certain fields that are not always going to be needed.
When I leave these blank in my code I get a error saying.
Column name or number of supplied values does not match table
definition.
This is how I have the database setup. SQL Server 2008
[youthclubid]
[youthclubname]
[description]
[address1]
[address2]
[county]
[postcode]
[email]
[phone]
Here is the code that I have connecting to the database and doing the insert.
connection.Open();
cmd = new SqlCommand("insert into youthclublist values ('" + youthclubname.Text + "', '" + description.Text + "','" + address1.Text + "','" + address2.Text + "', '" + county.Text + "', '" + postcode.Text + "', '" + email.Text + "', '" + phone.Text + "')", connection);
cmd.ExecuteNonQuery();
You have two major problems:
1) concatenating together your SQL statement is prone to SQL injection attacks - don't do it, use parametrized queries instead
2) You're not defining which columns you want to insert in your table - by default, that'll be all columns, and if you don't provide values for all of them, you'll get that error you're seeing.
My recommendation: always use a parametrized query and explicitly define your columns in the INSERT statement. That way, you can define which parameters to have values and which don't, and you're safe from injection attacks - and your performance will be better, too!
string insertStmt =
"INSERT INTO dbo.YouthClubList(Youthclubname, [Description], " +
"address1, address2, county, postcode, email, phone) " +
"VALUES(#Youthclubname, #Description, " +
"#address1, #address2, #county, #postcode, #email, #phone)";
using(SqlConnection connection = new SqlConnection(.....))
using(SqlCommand cmdInsert = new SqlCommand(insertStmt, connection))
{
// set up parameters
cmdInsert.Parameters.Add("#YouthClubName", SqlDbType.VarChar, 100);
cmdInsert.Parameters.Add("#Description", SqlDbType.VarChar, 100);
.... and so on
// set values - set those parameters that you want to insert, leave others empty
cmdInsert.Parameters["#YouthClubName"].Value = .......;
connection.Open();
cmdInsert.ExecuteNonQuery();
connection.Close();
}
The first major issue is that you are concatenating inputs in the query. This makes your application highly vulnerable to SQL Injection. Do not do this. Use a parametrized query.
The regular syntax for insert statement is like this:
Insert into <TableName> (Col1, Col2...Coln) values (val1, val2...valn)
If you need to insert only a selected set of columns, you need to provide the list of columns you are inserting data into in the column list.
If you do not specify the column list, the indication is that you are inserting data to each one of them.
So you may check for the input and if it is not there, you may omit the respective column.
The other better way is use a stored proc. That will ease out the issue.
This not way to do the code you make use of SqlParameter for this kind of statement.
So your code something like
SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Northwind_ConnectionString"].ConnectionString);
//Create Command object
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
try
{
// Create INSERT statement with named parameters
nonqueryCommand.CommandText = "INSERT INTO Employees (FirstName, LastName) VALUES (#FirstName, #LastName)";
// Add Parameters to Command Parameters collection
nonqueryCommand.Parameters.Add("#FirstName", SqlDbType.VarChar, 10);
nonqueryCommand.Parameters.Add("#LastName", SqlDbType.VarChar, 20);
nonqueryCommand.Parameters["#FirstName"].Value = txtFirstName.Text;
nonqueryCommand.Parameters["#LastName"].Value = txtLastName.Text;
// Open Connection
thisConnection.Open();
nonqueryCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
// Display error
lblErrMsg.Text = ex.ToString();
lblErrMsg.Visible = true;
}
finally
{
// Close Connection
thisConnection.Close();
}
You need to tell SQL server that which field you want to insert like
insert into youthclublist(youthclubid, youthclubname, ....) values ('" + youthclubname.Text + "', '" + description.Text + "'.....
and you are fine.
Though new into programming, the easiest way i know to insert into a database is to create a "save" stored procedure, which is then called up through your connection string. Believe me, this is the best way.
Another way around is to use LINQ to SQL. i found this much more easier. Follow this steps.
Add a new LINQ to SQL Classes to your project. Make sure the file extension is '.dbml'. Name it your name of choice say "YouthClub.dbml"
Connect your Database to Visual Studio using the Server Explorer
Drag your table to the OR Designer.(I'm not allowed to post images).
You can now save to the Database with this code
//Create a new DataContext
YouthClubDataContext db = new YouthClubDataContext();
//Create a new Object to be submitted
YouthClubTable newYouthClubRecord = new YouthClubTable();
newYouthClubRecord.youthlubname = txtyouthclubname.Text;
newYouthClubRecord.description = txtdescription.Text;
newYouthClubRecord.address1 = txtaddress1.Text;
newYouthClubRecord.address2 = txtaddress2.Text;
newYouthClubRecord.county = txtcounty.Text;
newYouthClubRecord.email = txtemail.Text;
newYouthClubRecord.phone = txtphone.Text;
newYouthClubRecord.postcode = txtpostcode.Text;
//Submit to the Database
db.YouthClubTables.InsertOnSubmit(newYouthClubRecord);
db.SubmitChanges();
Hope this time I have given a real answer

Categories