58

I am trying to create an SQL statement using user-supplied data. I use code similar to this in C#:

var sql = "INSERT INTO myTable (myField1, myField2) " +
          "VALUES ('" + someVariable + "', '" + someTextBox.Text + "');";

var cmd = new SqlCommand(sql, myDbConnection);
cmd.ExecuteNonQuery();

and this in VB.NET:

Dim sql = "INSERT INTO myTable (myField1, myField2) " &
          "VALUES ('" & someVariable & "', '" & someTextBox.Text & "');"

Dim cmd As New SqlCommand(sql, myDbConnection)
cmd.ExecuteNonQuery()

However,

  • this fails when the user input contains single quotes (e.g. O'Brien),
  • I cannot seem to get the format right when inserting DateTime values and
  • people keep telling me that I should not do this because of "SQL injection".

How do I do it "the right way"?

12
  • 5
    Note: This question is meant as a canonical question for people who cannot get their string-concatenated SQLs to work. If you want to discuss it, here is the corresponding meta question. Commented Feb 2, 2016 at 20:39
  • 4
    If you would like a more indepth look at what "SQL Injection" is and why it is dangerous see the question: "How can I explain SQL injection without technical jargon?" from our Information Security sister site. Commented Feb 2, 2016 at 21:11
  • 1
    You should wiki this, btw. Commented Feb 2, 2016 at 21:12
  • 2
    @Will: Won't CW'ing the question also CW all future answers, and, thus, discourage others from contributing better answers than mine? Commented Feb 2, 2016 at 21:19
  • 1
    @Igor: Good idea, done. I have also moved the VB version of the question code directly to the question, to make it obvious that this is about VB as well. Commented Mar 27, 2018 at 7:33

2 Answers 2

67

Use parameterized SQL.

Examples

(These examples are in C#, see below for the VB.NET version.)

Replace your string concatenations with @... placeholders and, afterwards, add the values to your SqlCommand. You can choose the name of the placeholders freely, just make sure that they start with the @ sign. Your example would look like this:

var sql = "INSERT INTO myTable (myField1, myField2) " +
          "VALUES (@someValue, @someOtherValue);";

using (var cmd = new SqlCommand(sql, myDbConnection))
{
    cmd.Parameters.AddWithValue("@someValue", someVariable);
    cmd.Parameters.AddWithValue("@someOtherValue", someTextBox.Text);
    cmd.ExecuteNonQuery();
}

The same pattern is used for other kinds of SQL statements:

var sql = "UPDATE myTable SET myField1 = @newValue WHERE myField2 = @someValue;";

// see above, same as INSERT

or

var sql = "SELECT myField1, myField2 FROM myTable WHERE myField3 = @someValue;";

using (var cmd = new SqlCommand(sql, myDbConnection))
{
    cmd.Parameters.AddWithValue("@someValue", someVariable);
    using (var reader = cmd.ExecuteReader())
    {
        ...
    }
    // Alternatively: object result = cmd.ExecuteScalar();
    // if you are only interested in one value of one row.
}

A word of caution: AddWithValue is a good starting point and works fine in most cases. However, the value you pass in needs to exactly match the data type of the corresponding database field. Otherwise, you might end up in a situation where the conversion prevents your query from using an index. Note that some SQL Server data types, such as char/varchar (without preceding "n") or date do not have a corresponding .NET data type. In those cases, Add with the correct data type should be used instead.

Why should I do that?

Other database access libraries

Sign up to request clarification or add additional context in comments.

5 Comments

Careful with the "other kind" statement -- SELECT won't work with cmd.ExecuteNonQuery()
@Hogan: True. I thought about giving a more complete example, but since this answer is mainly about transitioning from string-concatenated SQL to parameterized SQL, I did not want to bloat the answer by adding too much code that "won't change" (if it was ExecuteScalar before, it's ExecuteScalar afterwards).
@Heinze - I think I'd like a short bullet point under special cases saying something like "using parameters will work even if you are doing 'ExecuteQuery(), ExecuteReader(), ExecuteScalar()` or others.
@Hogan: I've expanded it a bit. I'm still trying to keep it short. There is no SqlCommand.ExecuteQuery().
Also worth reading can we stop using AddWithValue.
2

VB.NET Example Code

This is the example code for the wiki answer in , assuming Option Strict On and Option Infer On.

INSERT

Dim sql = "INSERT INTO myTable (myField1, myField2) " & 
          "VALUES (@someValue, @someOtherValue);"

Using cmd As New SqlCommand(sql, myDbConnection)
    cmd.Parameters.AddWithValue("@someValue", someVariable)
    cmd.Parameters.AddWithValue("@someOtherValue", someTextBox.Text)
    cmd.ExecuteNonQuery()
End Using

UPDATE

Dim sql = "UPDATE myTable SET myField1 = @newValue WHERE myField2 = @someValue;"

' see above, same as INSERT

SELECT

Dim sql = "SELECT myField1, myField2 FROM myTable WHERE myField3 = @someValue;"

Using cmd As New SqlCommand(sql, myDbConnection)
    cmd.Parameters.AddWithValue("@someValue", someVariable)
    Using reader = cmd.ExecuteReader()
        ' ...
    End Using
    ' Alternatively: Dim result = cmd.ExecuteScalar()
    ' if you are only interested in one value of one row.
End Using

1 Comment

Also worth reading can we stop using AddWithValue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.