Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

Use commandparameters instead of string concatenation

From Wiki

Jump to: navigation, search

To avoid SQL-injection (see Wikipedia:SQL injection) you should use the command parameters of the commandobject and not String concatenation.

This is how you would and could do it with string concatenation

  1. Dim _connection As System.Data.SqlClient.SqlConnection = New SqlClient.SqlConnection("Connectionstring")
  2.         _connection.Open()
  3.         Dim _command As New SqlClient.SqlCommand()
  4.         _command.Connection = _connection
  5.         _command.CommandType = CommandType.Text
  6.         _command.CommandText = "SELECT * FROM table1 WHERE field1 = '" & Me.Text & "'"
  7.         Dim _adapter As New SqlClient.SqlDataAdapter(_command)
  8.         Dim _datatable As New DataTable
  9.         _adapter.Fill(_datatable)

Especially this part is bad

  1. _command.CommandText = "SELECT * FROM table1 WHERE field1 = '" & Me.Text & "'"

We would need to change it like this.

  1. Dim _connection As System.Data.SqlClient.SqlConnection = New SqlClient.SqlConnection("Connectionstring")
  2.         _connection.Open()
  3.         Dim _command As New SqlClient.SqlCommand()
  4.         _command.Connection = _connection
  5.         _command.CommandType = CommandType.Text
  6.         _command.CommandText = "SELECT * FROM table1 WHERE field1 = @field1"
  7.         _command.Parameters.Add(New SqlClient.SqlParameter("@field1",SqlDbType.NVarChar,30)
  8.         _command.Parameters(0).Value = Me.Text
  9.         Dim _adapter As New SqlClient.SqlDataAdapter(_command)
  10.         Dim _datatable As New DataTable
  11.         _adapter.Fill(_datatable)

So we added a @field1 to our select statement and removed any single quotes the parameter will take care of that, which makes life eassier for us.

Then we create the parameter with the type and length matching our field in the table. And the we give it a value.

Much safer then using concatenation.

350 Rating: 2.8/5 (5 votes cast)