Travis Heeter
Travis Heeter

Reputation: 14054

How to add parameters to WebMatrix Database.Query?

Using Database.Query has has made a huge improvement on readability in my code:

String Select = 'sp_getAllUsers';
WebMatrix.Data.Database DB = WebMatrix.Data.Database.Open(MyConString);
var data = DB.Query(Select);

I'd like to switch to a non-stored procedure query. The MSDN says there's an optional parameter to the Query Method, Object[], that can be passed as SQL parameters, however they don't have any further information about it.

So I have two questions:

Here's an abridged version of what I have tried:

Select = "Select * From Users Where first_name = "Foo" AND last_name = "Bar"

// Like Javascript
Object[] params = {"first_name" : "Foo"}, {"last_name" : "Bar"};

// More Like What I think it will be
Object[] Params = (String Name = "first_name", String First_Name = "Foo");

var data = DB.Query(Select, params);

All the sources I've looked at only seem to reference the old way. This is close, but he doesn't use the parameter parameter of the Query method.

Upvotes: 3

Views: 1258

Answers (1)

Carl Prothman
Carl Prothman

Reputation: 1551

Try using this syntax:

string selectCommand = "sp_getAllUsers(@0, @1)";
// selectCommand = "Select * From Users Where first_name = @0 AND last_name = @1";
...
var data = DB.Query(selectCommand, "Foo", "Bar");

More info, see: http://www.aspnet101.com/2010/07/webmatrix-tutorial-working-with-data/

Also, using a Parameter will always prevent SQL Injection as it always double quote a single quote.

Upvotes: 5

Related Questions