0

I'm trying to figure out if there is a better way to do this

Dim cmd As New SqlCommand
Dim sel As String
Dim obj As New DataHandler
sel = String.Format("SELECT * FROM Customers WHERE Country LIKE '{0}%'", txt_Input.Text)
cmd.CommandText = sel

Me.dgv_Customers.DataSource = obj.SqlDataRetriever(cmd)

Basically what im trying to do is have a textbox that whenever I type a letter, the grid refreshes itself by sending a Query to my SQL server searching for whatever its in the textbox using the LIKE() from SQL. I've been reading about SQL injection and so far everyone suggests to use parameter values (@value) for user input, but if I try to replace the {0} with that it doesn't work. I just wanna make sure that this is a valid way of doing this.

Thanks

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
R.Arg1989
  • 25
  • 6

1 Answers1

0

Instead just concatenate the string like below. You should consider using parameterized query to avoid SQL Injection.

sel = "SELECT * FROM Customers WHERE Country LIKE '" + txt_Input.Text + "%'";

Use a parameterized query rather. See This Post

Dim cmd as New SqlCommand("SELECT * FROM Customers WHERE Country LIKE @param")
cmd.Parameters.Add("@param", txt_Input.Text +"%")
Community
  • 1
  • 1
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • Wouldn't it be possible for someone to do something like : "..... ; drop table Customers -- ? – R.Arg1989 Oct 01 '15 at 04:04
  • @R.Arg1989, absolutely and that's what SQL injection is all about. – Rahul Oct 01 '15 at 04:05
  • TYVM! :) This works perfectly. I guess that since I'm using a place holder the single quotes aren't necessary and the SQL query still goes through. – R.Arg1989 Oct 01 '15 at 04:21