How to add parameters to WebMatrix Database.Query?

浪尽此生 提交于 2019-12-23 19:14:34

问题


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:

  • How can I create a Object[]?
  • Will adding parameters in this way prevent hacking threats, such as SQL Injection?

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.


回答1:


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.



来源:https://stackoverflow.com/questions/30354882/how-to-add-parameters-to-webmatrix-database-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!