MYSQL insert

I’m trying to insert values from a variable into a test MYSQL. It works
from a fixed value but not if the value is in a variable.

require ‘mysql’
$test = “ABC”

#db.query(‘insert into etf_list values ($test)’)
>> in `query’: Column ‘test’ cannot be null (Mysql::Error)

db.query(‘insert into etf_list values (“ABC”)’)
>> Works

Thanks
Jeff B.

On Mon, Jul 13, 2009 at 17:12, Jeff B.[email protected] wrote:

I’m trying to insert values from a variable into a test MYSQL. It works
from a fixed value but not if the value is in a variable.

require ‘mysql’
$test = “ABC”

#db.query(‘insert into etf_list values ($test)’)

in `query’: Column ‘test’ cannot be null (Mysql::Error)

use double quotes, and enclose with “#{}”. single quotes don’t
expand variables.
i.e. db.query(|insert into etf_list values ("#{$test}")")

j.

On Jul 13, 2009, at 11:24 AM, Jano S. wrote:

use double quotes, and enclose with “#{}”. single quotes don’t
expand variables.
i.e. db.query(|insert into etf_list values ("#{$test}")")

j.

Also, this is ruby, not perl. Unless you have a "really good
reason"™ for using $test which is a global variable, you probably
just need a plain old local varialble here:

test = “ABC” # or test=‘ABC’ since either style of quotes is fine
for most strings with no interpolation

db.query(“insert into etf_list values (”#{test}")")

There’s actually another form of string literal that I often find
useful when quotes are concerned: %{}
(and you can leave out the parentheses in many instances and, IMHO,
this is one)[1]

db.query %{insert into etf_list values ("#{test}")}

-Rob

[1] You might also take a few minutes to read James Edward G. II’s
post about when to use parentheses and when to leave them out.
http://blog.grayproductions.net/articles/
do_i_need_these_parentheses

Rob B. http://agileconsultingllc.com
rem[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs