4

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.

1
  • @user2124495 you will end up in Sql Injection. please use parametrized queries Commented Mar 18, 2013 at 11:43

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Got that to work now, but now that I don't have the 'query' variable, how would I get the result?
You can either use SqlDataReader to read data or Populate a DataSet/DataTable from command
0
var pageID=1;
var query = db.Query("SELECT * FROM pageinfo WHERE pageID = '"+ PAGEid +"');

1 Comment

Don't. Read more about SQL Injection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.