简体   繁体   English

剃刀和CSHTML:如何为select语句执行db.Execute?

[英]razor and cshtml: how to db.Execute for select statement?

I am doing a quick CSHTML page for the purpose of testing. 我正在做一个快速的CSHTML页面以进行测试。

I need to access database based on the id parameter on the URL: 我需要基于URL上的id参数访问数据库:

var id = Request.QueryString["id"];
var db = Database.Open("mydatabase_connection");
var query = "select * from myrecord where id =  " + id;
var row = db.QuerySingle(query);

//i am able to display the field (called name) of the selected record in the following way: //我可以通过以下方式显示所选记录的字段(称为名称):

@row.name

Obviously, the above approach is subject to security attack. 显然,上述方法容易受到安全攻击。 I am hoping to retrieve the record the following way: 我希望通过以下方式检索记录:

var query = "select * from myrecord where id=@0";
var row = db.Execute(query, id);

However, I get runtime error when retrieving the field value: 但是,检索字段值时出现运行时错误:

@row.name

What is the correct way of getting the "row" in the second approach? 在第二种方法中获得“行”的正确方法是什么?

Thanks and regards. 谢谢并恭祝安康。

Database.Execute is for executing a non-query SQL statement and returns the count of records affected by the SQL statement as an Int . Database.Execute用于执行非查询SQL语句,并以Int返回受SQL语句影响的记录数。

I think the method you want to use really is Database.QuerySingle , which returns an Object . 我认为您真正想要使用的方法是Database.QuerySingle ,它返回一个Object

ie. 即。

var query = "select * from myrecord where id=@0";
var row = db.QuerySingle(query, id);

Razor: 剃刀:

  @row.name

As far as safety from SQL injection goes, this approach is safe. 就SQL注入的安全性而言,这种方法是安全的。 You are passing the URL value into your query as a parameter . 您正在将URL值作为参数传递到查询中。

The unsafe way to run the query would be with string concatenation: 运行查询的不安全方法是使用字符串连接:

   var query = "select * from myrecord where id=" + id; 

Don't do this! 不要这样! It allows for a malicious user to append SQL statements to your query! 它允许恶意用户将SQL语句附加到您的查询中! Always use parameterized queries instead. 始终改用参数化查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM