how do I put an int variable in sql?
x
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';";
Advertisement
Answer
Please don’t use concatenated values in your SQL command. You are exposing your application to SQL Injection Attacks
. Read more here.
Use SqlParameters instead. It is the proper way to do and safer when you are running sql commands against your database from your application.
If a value is int covert it to integer:
command.Parameters.AddWithValue("@id", int.Parse(Request.Form["id"]));
Here is a example of how to use parameters.
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();
}
More about SqlCommand here.