简体   繁体   English

在rails中没有真正的“预备声明”?

[英]There is no real 'prepared statement' in rails?

When we use ActiveRecord, we can use: 当我们使用ActiveRecord时,我们可以使用:

User.find(:first, :conditions=>["name=?", name])

It looks like ActiveRecord are using 'prepared statement', but after looking into the code, I found ActiveRecord just use String.dup and connection.quote() to adjust the content to build a sql, not like Java. 看起来ActiveRecord正在使用'prepared statement',但在查看代码之后,我发现ActiveRecord只是使用String.dupconnection.quote()调整内容来构建一个sql,而不是像Java一样。

So, there is no real prepared statment in raiils? 那么,在raiils中没有真正prepared statment吗? And why rails doesn't provide it? 为什么rails不提供它?

If by prepared statement you mean a piece of SQL that is held in a compiled form for more efficient execution, then you're correct: it's not something implemented in Rails. 如果通过预处理语句表示一个以编译形式保存以便更有效执行的SQL,那么你是正确的:它不是在Rails中实现的。 There are several reasons for this: 有几个原因:

  1. Rails is the web framework - it doesn't know or care about databases. Rails是Web框架 - 它不知道或不关心数据库。 By default, Rails uses 默认情况下,Rails使用
    • ActiveRecord for object-relational mapping. ActiveRecord用于对象关系映射。 You can change this if you want to - it doesn't have to be a RDBMS even. 如果您愿意,可以更改它 - 它甚至不必是RDBMS。
    • ActiveRecord doesn't know about specific database platforms. ActiveRecord不了解特定的数据库平台。 For that it relies on "adapters", which translate AR's requirements into platform-specific SQL. 为此,它依赖于“适配器”,它将AR的需求转换为特定于平台的SQL。
    • Some RDBMSs that have AR adapters support prepared statements (or equivalent) but others don't. 一些具有AR适配器的RDBMS支持预处理语句(或等效语句),但其他RDBMS不支持。

Rails 3.1 (or greater) supports prepared statements. Rails 3.1(或更高版本)支持预准备语句。 Every new query you make will be added to pool of prepared statement. 您创建的每个新查询都将添加到预准备语句池中。 If you are are using MySql DB it still won't support prepared statement because using prepared statements in MySql reduces the performance compare to without prepared statement. 如果您正在使用MySql DB,它仍然不支持预准备语句,因为在没有预准备语句的情况下,在MySql中使用预准备语句会降低性能。 Here is the nice article by Pat Shaughnessy on this. Pat Shaughnessy关于此的好文章。

In many (most?) ways, a DB View is a prepared statement. 在许多(大多数?)方式中,DB View是一个准备好的语句。 And it is easy to use views with ActiveRecord. 使用ActiveRecord很容易使用视图。 Just declare the view in your DB (I use rake tasks) and then access it via ActiveRecord. 只需在数据库中声明视图(我使用rake任务),然后通过ActiveRecord访问它。

Works great for read-only access to complicated SQL. 适用于对复杂SQL的只读访问。 Saves the DB from many of the steps required to parse/compute SQL. 从解析/计算SQL所需的许多步骤中保存数据库。

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

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