如何向WebMatrix Database.Query添加参数? [英] How to add parameters to WebMatrix Database.Query?
问题描述
使用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);
我想切换到非存储过程查询. MSDN说查询方法的一个可选参数,Object[]
,可以作为SQL参数传递,但是它们没有任何进一步的信息.
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.
所以我有两个问题:
- 如何创建
Object[]
? - 以这种方式添加参数是否可以防止诸如SQL注入之类的黑客威胁?
这是我尝试过的内容的简化版本:
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);
我看过的所有资源似乎都引用了旧方法. 此已关闭,但他未使用查询的parameter参数方法.
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.
推荐答案
尝试使用以下语法:
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");
更多信息,请参见: http://www.aspnet101.com/2010/07/webmatrix-tutorial-working-with-data/
More info, see: http://www.aspnet101.com/2010/07/webmatrix-tutorial-working-with-data/
此外,使用参数将始终阻止SQL注入,因为它总是将双引号引起来.
Also, using a Parameter will always prevent SQL Injection as it always double quote a single quote.
这篇关于如何向WebMatrix Database.Query添加参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!