Search code examples
c#sql-serverconnection

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.."


Solution

  • 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]);