Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# Variables in SQL Query

Tags:

c#

sql

asp.net

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.

like image 997
user2124495 Avatar asked Dec 06 '22 08:12

user2124495


1 Answers

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

like image 93
Habib Avatar answered Dec 22 '22 12:12

Habib