I have a problem with my sql query. I have a database in sqlserver.
int number = int.Parse(textbox.Text);
var sqlconn = new SqlConnection(@"Server=(localdb)\MSSQLLocalDB; AttachDbFileName=|DataDirectory|db.mdf;");
sqlconn.Open();
var sqlcomm = new SqlCommand("SELECT * FROM table WHERE title = number", sqlconn);
what is the correct syntax for this: title = number?
I suggest using parameters to avoide SQL Injection .
Could look like this.
using (SqlCommand command = new SqlCommand("SELECT * FROM table WHERE title = @Number", connection))
{
command.Parameters.Add(new SqlParameter("@Number", int.Parse(textbox.Text)));
//read data
}
you can add the integer inline by doing the following
var sqlcomm = new SqlCommand("SELECT * FROM table WHERE title = " + number.ToString(), sqlconn);
or you can add it as a parameter like the following:
var sqlcomm = new SqlCommand("SELECT * FROM table WHERE title = @num", sqlconn);
sqlcomm.Parameters.AddWithValue("@num", number);
This is a very basic question which you could have easily solved by just google-ing it.
Anyways, you want to use parameterized SQL command here.
var sqlcomm = new SqlCommand("SELECT * FROM table WHERE title = @number", sqlconn);
SqlParameter param = new SqlParameter();
param.ParameterName = "@number";
param.Value = int.Parse(textbox.Text);
sqlcomm.Parameters.Add(param);
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.