[.net] SQL and VB.Net

Started by
10 comments, last by bgreen 19 years ago
How can I use variables in my SQL statements with vb.net?

Dim userparam As String = textbox.text
Dim connect As New OleDbConnection(connectionString)
Dim commandString As String = "SELECT * FROM table WHERE column = :userparam"
Dim dataAdapter As New OleDbDataAdapter(commandString, connect)
This isn't working for me any help would be great thanks.
Advertisement

I always put string between ' '. So maybe:

Dim commandString As String = "SELECT * FROM table WHERE column = ':userparam'"

Or maybe your connection is wrong. What kind of error do you get? Syntax error?

Edo
Edo
when I use ':userparam' I get null values the error occurs when I dont use the single quotes. When I hardcode the userparam like

Select * ...Where column = 'Tom'

it works fine.

edit: error message = No value given for one or more required parameters.
Would stored procedures help? They use the @ symbol instead of :
Be careful using the 'string manipulation' way. SQL Injection is just around the corner!

Cheers
Is it better to pass objects (OleDbCommand) to DataAdpater rather than strings?
[google] for SQL injection and you'll know.

Cheers
As said before, you probably should avoid using this if this due to security risks, but anyway, this is what you probably want:

Dim userparam As String = textbox.text
Dim connect As New OleDbConnection(connectionString)
Dim commandString As String = "SELECT * FROM table WHERE column = '" & userparam & "'"
Dim dataAdapter As New OleDbDataAdapter(commandString, connect)

This will concatenate the select string with your userparam string and produce what hopefully is a valid connection string.

Again, this is very dangerous to put out there - a clever guy could manipulate the statement to do just about anything with your database.
Please be smart and use something like this:

Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM table WHERE userparam= @userparam", connect)cmd.Parameters.Add("@MyValue", OleDbType.VarChar).Value = userparamDim dataAdapter As New OleDbDataAdapter(cmd)


Please, ALWAYS use parameters and make the world a bit safer :)

Regards,
Andre
Andre Loker | Personal blog on .NET
Always use parameterized queries when dealing with databases. Always. IIRC, the names of the parameters are ignored, so you should call query.Parameters.Add() in the order that you specify the parameters in the query string.

I'd recommend just using '?'s in place of parameter names in the query string to avoid confusion. Your query would look like this:
Dim commandString As String = "SELECT * FROM table WHERE column = ?"
Free Mac Mini (I know, I'm a tool)

This topic is closed to new replies.

Advertisement