Dan Brooks
Dan Brooks

Reputation: 89

Basic SQL - SELECT

So I've got this code:

query2 = "SELECT * from Clicking WHERE ID = '" + ID + "'";

And it seems to make problems with the script, probably I'm mistaken with something here.

For instance, when I write this:

query2 = "SELECT * from Clicking WHERE ID = 3";

..this works just fine, and the script continue with no problems. But with my original code it shows me this error:

OleDbException was unhandled by user code

An exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll but was not handled in user code

Any suggestions how to make this work?

Upvotes: 1

Views: 87

Answers (2)

pkatsourakis
pkatsourakis

Reputation: 1082

The way you have the query written it will be like this:

SELECT * from Clicking WHERE ID = '3'

The '' around a number means it will look for an ID as a string that is equal to 3. So you want to remove the single quotes around the number, so it will search for a number that is equal to 3, or whatever number you use. This is what you want:

query2 = "SELECT * from Clicking WHERE ID = " + ID;

Upvotes: 1

Selman Genç
Selman Genç

Reputation: 101681

When you use single quotes the 3 is treated as string, and probably your ID column is an int, that's why you are getting the exception .

Also do not use string concatenation, use parameterized queries to prevent SQL injection attacks

query2 = "SELECT * from Clicking WHERE ID = @id";

using(var cmd = new SqlCommand(query2, connection))
{
   cmd.Parameters.AddWithValue("@id", ID);  
   ...
}

Upvotes: 5

Related Questions