本文介绍了如何在C#和SQL Server中更新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的过程,该过程应该更新具有3列的表中的得分: id ,昵称, scor .
This is my procedure which should update the score in a table with 3 columns: id, nickname, scor.
Otherform.id1 是需要更新的用户的 id ,它是从登录表单中获取的.
Otherform.id1 is the id of the user that needs the update and it's taken from the login form .
void update() { SqlConnection c = new SqlConnection(co); c.Open(); string up1 = "Update Scoruri Set Scor='" + Convert.ToInt32(scor1) + "' where ID='" + otherForm.id1 + ";'"; //z.Parameters.AddWithValue("@y", scor1); SqlCommand comm = new SqlCommand(up1, c); comm.ExecuteNonQuery(); string up2= "'Update Scoruri Set scor='" +Convert.ToInt32(scor2) + "' where ID='" + otherForm.id2 + "';'"; SqlCommand h = new SqlCommand(up1, c); h.ExecuteNonQuery(); c.Close(); } 推荐答案您没有确切地说出问题是什么,但是我发现您的代码中有一些错误.
You didn't tell what is wrong exactly but I see a few things wrong in your code.
- 您应始终使用 参数化查询 .这种类型的字符串连接可用于 SQL注入 攻击.li>
- 我假设您的 Scor 和 ID 列是数字而不是字符.这就是为什么您不应该在其中使用单引号.使用参数化查询,您无需担心.
- 使用 使用语句进行处理您的 SqlConnection 和 SqlCommand .
- 在第二个 SqlCommand (即 h )中,您正在执行第一个命令( up1 ),而不是第二个命令( up2 ).
- You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
- I assume your Scor and ID columns are numeric, not character. That's why you should not use single quotes with it. With parameterized queries, you don't need to worry about that.
- Use using statement to dispose your SqlConnection adn SqlCommand.
- In your second SqlCommand (which is h) you are executing first command (up1) not second one (up2).
作为一个例子;
void Update() { using(SqlConnection c = new SqlConnection(co)) using(SqlCommand comm = c.CreateCommand()) { string up1 = "Update Scoruri Set Scor=@scor where ID=@id"; comm.CommandText = up1; comm.Parameters.AddWithValue("@scor", Convert.ToInt32(scor1)); comm.Parameters.AddWithValue("@id", otherForm.id1); c.Open(); comm.ExecuteNonQuery(); comm.Parameters.Clear(); comm.Parameters.AddWithValue("@scor", Convert.ToInt32(scor2)); comm.Parameters.AddWithValue("@id", otherForm.id2); comm.ExecuteNonQuery(); } }更多推荐
如何在C#和SQL Server中更新值?
发布评论