user2124495
user2124495

Reputation: 59

Using C# Variables in SQL Query

I'm very new to this. There might be something obvious I'm completely missing, but...

When making an SQL query (ASP.NET with C#) I can get this:

var query = db.Query("SELECT * FROM pageinfo WHERE pageID = 1");

to work, and yet this:

var pageID=1;
var query = db.Query("SELECT * FROM pageinfo WHERE pageID = @pageID");

does not.

Basically, all I want to do is place a variable into the query. Is there some special syntax for doing this?

Thanks.

Upvotes: 4

Views: 4499

Answers (2)

Habib
Habib

Reputation: 223207

Is there some special syntax for doing this?

Yes, Use SQLParameter.

Something like:

SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = @pageID");
cmd.Parameters.AddWithValue("@pageID", 2);

Your current method db.Query seems to be a your own implementation. You can overload that method to receive a list of SqlParameter and then add those parameters to your command. This will prevent you from SQL Injection

Upvotes: 15

felix Antony
felix Antony

Reputation: 1460

var pageID=1;
var query = db.Query("SELECT * FROM pageinfo WHERE pageID = '"+ PAGEid +"');

Upvotes: 0

Related Questions