如何在SQL中放置一个int变量?
int x = Convert.ToInt32(Session["id"]);
string MySQL = @"UPDATE users SET
email = '"+Request.Form["email"]+"', pname =
'"+Request.Form["pname"]+"', accountname=
'"+Request.Form["accountname"]+"', pid = '"+Request.Form["pid"]+"', age =
'"+Request.Form["age"]+"',passw = '"+Request.Form["passw"]+"' where
id='x';";
答案 0 :(得分:0)
请不要在SQL命令中使用串联值。您正在将您的应用程序暴露于SQL Injection Attacks
。了解更多here。
改用SqlParameters。当您从应用程序对数据库运行sql命令时,这是正确且安全的方法。
如果值是int隐蔽值,则为整数:
command.Parameters.AddWithValue("@id", int.Parse(Request.Form["id"]));
这里是如何使用参数的示例。
string mySql = @"UPDATE users SET email = @email, pname = @pname, accountname = @accountname, pid = @pid, age = @age, passw = @passw where id = @id;";
string connectionString = "Server=localhost\\SQLEXPRESS;Database=[your database];User Id=sa;Password=[your password];";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(mySql, connection);
command.Parameters.AddWithValue("@email", Request.Form["email"]);
command.Parameters.AddWithValue("@pname", Request.Form["pname"]);
command.Parameters.AddWithValue("@accountname", Request.Form["accountname"]);
command.Parameters.AddWithValue("@pid", Request.Form["pid"]);
command.Parameters.AddWithValue("@age", int.Parse(Request.Form["age"]));
command.Parameters.AddWithValue("@passw", Request.Form["passw"]);
command.Parameters.AddWithValue("@id", int.Parse(Request.Form["id"]));
connection.Open();
command.ExecuteNonQuery();
}
有关SqlCommand here的更多信息。