How to use parameters "@" in an SQL command in VB

You are on the right path to avoiding Bobby Tables, but your understanding of @ parameters is incomplete.

Named parameters behave like variables in a programming language: first, you use them in your SQL command, and then you supply their value in your VB.NET or C# program, like this:

MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = @TicBoxText WHERE Number = 1", dbConn)
MyCommand.Parameters.AddWithValue("@TicBoxText", TicBoxText.Text)

Note how the text of your command became self-contained: it no longer depends on the value of the text from the text box, so the users cannot break your SQL by inserting their own command. @TicBoxText became a name of the variable that stands for the value in the text of the command; the call to AddWithValue supplies the value. After that, your ExecuteReader is ready to go.


There are a number of improvements in here:

Using dbConn As New SqlConnection("server=.\SQLEXPRESS;Integrated Security=SSPI; database=FATP"), _
      MyCommand As SqlCommand("UPDATE SeansMessage SET Message = @Message WHERE Number = 1", dbConn)

    'Make sure to use your exact DbType (ie: VarChar vs NVarChar) and size
    MyCommand.Parameters.Add("@Message", SqlDbType.VarChar).Value = TicBoxText.Text

    dbConn.Open()
    MyCommand.ExecuteNonQuery() ' don't open a data reader: just use ExecuteNonQuery
End Using 'Using block will close the connection for you