Using Connection As SqlConnection = New SqlConnection(ConnectionString)
Connection.Open()
Dim CmdText As String = "INSERT INTO [Person] (FirstName, LastName) " & _
"VALUES ('" & txtFirstname.Text & "', '" & txtLastname.Text & ")"
Using cmd As SqlCommand = New SqlCommand(CmdText, Connection)
cmd.ExecuteNonQuery()
End Using
Connection.Close()
End Using
While code like this will work sometimes, it isn’t ideal for a number of reasons:
Using Connection As SqlConnection = New SqlConnection(ConnectionString)
Connection.Open()
Dim CmdText As String = "INSERT INTO [Person] (FirstName, LastName) " & _
"VALUES (@lastname, @firstname)"
Using cmd As SqlCommand = New SqlCommand(CmdText, Connection)
With cmd.Parameters
.AddWithValue("@lastname", txtLastname.Text)
.AddWithValue("@firstname", txtFirstname.Text)
End With
cmd.ExecuteNonQuery()
End Using
Connection.Close()
End Using
In the command text, we’ve added
@lastname and
@firstname as placeholders or parameters, which then must be added, along with their values, to the parameters collection of the command object. The "AddWithValue" method is convenient for adding parameters with their values. .NET 1.x users will not have access to this method. There is an overload of "Add" that allows you to specify a parameter value, but this was deprecated by the AddWithValue method as explained in
the MSDN documentation.
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (3)
Commented:
I can't read about SQL Injection without thinking of...
A database guru or geek will,
Say: No DBA elsewhere's my equal.
I can easily handle
a "Bobby'; DROP TABLE" vandal,
'cuz I always escape all my SQL!
But parameterizing the input trumps escaping it, every time ;-)
Author
Commented:Commented: