简体   繁体   English

ado.net中的C#更新

[英]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语句在语法上是错误的

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 SQL注入容易

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));  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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