I'm new to Ruby and I want to try to access a MySQL database:
require 'rubygems'
require "dbi"
class DBConnection
attr_accessor :dbh
#Connect to db
def connect?(driver_url,user,pass)
begin
@dbh = DBI.connect(driver_url, user,pass);
return true
rescue DBI::DatabaseError => e
puts "Error message: #{e.errstr}"
@dbh.rollback
return false
ensure
@dbh.disconnect if !dbh
end
end
def execute_customize(query,params)
stm = @dbh.prepare(query)
if( (params != nil) && !(params.empty?) )
stm.execute(params)
else
stm.execute
end
header = false
stm.fetch do |row|
if (!header)
puts("ID Name")
header = true
end
puts("#{row[0]} #{row[1]}")
end
end
end
db = DBConnection.new
db.connect?("DBI:Mysql:test:localhost", "root", "123456")
db.execute_customize("SELECT * FROM test.employee WHERE name = ? OR name = ? ",*["John","Terry"])
But the above returns the following error:
in `execute_customize': wrong number of arguments (3 for 2) (ArgumentError)
But the execution is successful with:
dbh.execute_customize("SELECT * FROM test.employee WHERE name = ?",*["John"])
What am I doing wrong?
Demo data from employee table :
+------+-------+
| id | name |
+------+-------+
| 1 | John |
| 2 | Terry |
| 3 | Vidal |
| 4 | CR7 |
| 5 | M10 |
| 6 | R10 |
| 7 | F4 |
+------+-------+
// Update : Your comment almost told me using IN in query, but if with other query like :
SELECT * FROM test.employee WHERE name = ? and id > ?
I still need a way to passing seperate paramer to every "?" character
Employee.where(name: ['John', 'Terry'])dbh? How did you create it? The mysql2 gm doesn't seem to have anexecuteat all and the old mysql gem'sexecutedoesn't work like that.