简体   繁体   中英

How do I refer to my form elements' values in a query? C# MSSQL

I'm trying to insert data from my textbox value to the database. This code works perfectly fine

SqlCommand query = new SqlCommand(@"INSERT INTO GuestTable (CustomerName, Address) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')", con);

But I only need to insert that data to a specified ID. So I figured I need to add this:

  WHERE CustomerID = '" +Convert.ToInt32(textBox3.Text)+"'

But that line gives an error only after I ran the program saying, "Error near 'WHERE' keyword.."

In short, you do not do it like that. You should never use string concatenation within an SQL query. In C#, you should be using Parameterized Queries. Then, you can use the methods C# provides to insert your variables into the query.

Here is an example taken from Using Parameterized Query to Avoid SQL Injection

string sql = "select count(UserID) from user_login where UserID=@UserID and pwd=@pwd";  
SqlCommand cmd = new SqlCommand(sql, con);  
SqlParameter[] param = new SqlParameter[2];  
param[0] = new SqlParameter("@UserID", txtUSerID.Text);  
param[1] = new SqlParameter("@pwd", txtPwd.Text);  
cmd.Parameters.Add(param[0]);  
cmd.Parameters.Add(param[1]);

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.

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