开发者

There is no real 'prepared statement' in rails?

When we use ActiveRecord, we can use:

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, n开发者_如何转开发ot like Java.

So, there is no real prepared statment in raiils? And why rails doesn't provide it?


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. There are several reasons for this:

  1. Rails is the web framework - it doesn't know or care about databases. By default, Rails uses
    • ActiveRecord for object-relational mapping. You can change this if you want to - it doesn't have to be a RDBMS even.
    • ActiveRecord doesn't know about specific database platforms. For that it relies on "adapters", which translate AR's requirements into platform-specific SQL.
    • Some RDBMSs that have AR adapters support prepared statements (or equivalent) but others don't.


Rails 3.1 (or greater) supports prepared statements. 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. Here is the nice article by Pat Shaughnessy on this.


In many (most?) ways, a DB View is a prepared statement. And it is easy to use views with ActiveRecord. Just declare the view in your DB (I use rake tasks) and then access it via ActiveRecord.

Works great for read-only access to complicated SQL. Saves the DB from many of the steps required to parse/compute SQL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜