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) \" +
This is the example code for the wiki answer in vb.net, 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