Inserting to the mysql table in ruby

I have a table and a phonebook program that I get information from users
and insert into the table , but because of I use two variable first and
second for information of users I can’t Insert them into the table. my
code is below :

def inserting
first = gets
second = gets
@connect.query(‘INSERT INTO person VALUES(first,second)’)
end

please help me to solve this problem.

amir e. wrote in post #1030005:

I have a table and a phonebook program that I get information from users
and insert into the table , but because of I use two variable first and
second for information of users I can’t Insert them into the table. my
code is below :

def inserting
first = gets
second = gets
@connect.query(‘INSERT INTO person VALUES(first,second)’)
end

That’s not complete code. What’s the type of @connect? That is, what
database API are you using?

There are lots you could be using. Low-level: ruby-mysql and mysql-ruby.
Medium-level: DBI. High-level: ActiveRecord, Sequel, DataMapper (which
also let you drop out to low-level queries like you show).

Also, what documentation did you follow to get to this point? Post the
URL. It probably contains how to insert placeholders to bind values, or
to quote values so that they can be interpolated safely into a SQL
string.

For example, DBI lets you do something like this (off the top of my
head):

@connect.query('INSERT INTO person VALUES(?,?)',first,second)

Assuming you’re using a low-level gem like ruby-mysql like
Brian mentioned above, the query might have thrown an error
because of forgotten single quotes around string values.

@connect.query(‘INSERT INTO person VALUES(first,second)’)

should probably be:

@connect.query(“INSERT INTO person VALUES(’#{first}’, ‘#{second#}’”)

And, like Brian mentioned, try the DBI gem, which isn’t overkill
for anyone’s needs because it protects against SQL injection attacks.

-Luke

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