0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

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+"'";
Faisal Hameed
  • 104
  • 1
  • 9
0

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

Philip Stuyck
  • 7,344
  • 3
  • 28
  • 39