Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to prepare raw sql statements with dynamic binding in Rails using ActiveRecord::ConnectionAdapters?
    primarykey
    data
    text
    <p>I use MySQL DB and MySQL2 as adapter.</p> <p>I want to execute custom sql-statements in Rails.</p> <p>I need a method that would allow to prepare sql-statements like in PHP, like this:</p> <pre><code>stmt = prepare("INSERT INTO tab (col1, col2) VALUES (?, ?)", ["foo", "bar"]) </code></pre> <p>I found, though, that neither ActiveRecord nor MySQL2 have no such methods.</p> <p>But I found that there are several <code>exec_*</code> methods in <a href="http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-exec_insert" rel="nofollow">ActiveRecord::ConnectionAdapters::AbstractAdapter</a> and I think they are exactly for my task but don't know how to use them, their API documentation has very little info:</p> <blockquote> <p>exec_insert(sql, name, binds)</p> <p>Executes insert sql statement in the context of this connection using binds as the bind substitutes. name is the logged along with the executed sql statement.</p> </blockquote> <p>I've tired this</p> <pre><code>sql = "INSERT INTO tab (col1, col2) VALUES (?, ?)" r = ActiveRecord::Base.connection().exec_insert(sql, "someName", [10, "foo"]) puts r </code></pre> <p>But got an error:</p> <pre><code>`query': Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?)' </code></pre> <p>So how to use these methods? What is a <code>name</code> attribute? What is a type of a <code>bind</code> parameter? How to write sql-statement, what to put instead of <code>?</code>?</p> <p><strong>UPD:</strong></p> <p>I've written <code>prepare</code> method to use in Rails. <a href="https://github.com/wzup/rails_prepare" rel="nofollow">See in github</a>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload