简体   繁体   中英

C# Update in ado.net

Old records are not deleting. Update acts like insert.

cn.Open();

string gen;
if (radioButton1.Checked == true)
    gen = "Male";
else
    gen = "Female";
string clas = null;

clas = comboBox1.Text;

string section = null;
section = comboBox2.Text;
SqlCommand cmd = new SqlCommand("update studetail set name='" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "' where studentno='" + textBox1.Text + "'");
cmd.Connection = cn;

int n = cmd.ExecuteNonQuery();

update acts like insert.

That's obvious cause you made it like so. Your below UPDATE statement is syntactically wrong

update studetail set name='" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section 

It rather should be

update studetail set name='" + textBox2.Text + "',' gender = " + gen + "','" ...

Finally, you should consider using parameterized queries instead of concatanating user input likewise you are doing. It's prone to SQL Injection

SqlCommand cmd = new SqlCommand("update studetail set name= @name, gender = @gender, clas = @clas, section = @section where studentno = @studentno");

cmd.Parameters.Add(new SqlParameter("name", textBox2.Text));  
cmd.Parameters.Add(new SqlParameter("gender", gen));  
cmd.Parameters.Add(new SqlParameter("clas", clas));  
cmd.Parameters.Add(new SqlParameter("section", section));  
cmd.Parameters.Add(new SqlParameter("studentno", textBox1.Text));  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM