简体   繁体   中英

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, not 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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