Skip to content

Instantly share code, notes, and snippets.

@brianstorti
Created May 30, 2011 02:07
Show Gist options
  • Save brianstorti/998361 to your computer and use it in GitHub Desktop.
Save brianstorti/998361 to your computer and use it in GitHub Desktop.
DBI example
require 'dbi'
begin
dbh = DBI.connect("DBI:Mysql:test:localhost", "root", "")
row = dbh.select_one("SELECT VERSION()")
puts "Server version: #{row[0]}"
rescue DBI::DatabaseError => e
puts "An error occurred"
ensure
dbh.disconnect if dbh
end
#insert
sth = dbh.prepare("INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (?, ?, ?, ?, ?)")
sth.execute('John', 'Poul', 25, 'M', 2300)
sth.execute('Zara', 'Ali', 17, 'F', 1000)
sth.finish
dbh.commit # or dbh.rollback
#select
sth = dbh.prepare("SELECT * FROM EMPLOYEE WHERE INCOME > ?")
sth.execute(1000)
sth.fetch do |row|
printf "First Name: %s, Last Name : %s\n", row[0], row[1]
printf "Age: %d, Sex : %s\n", row[2], row[3]
printf "Salary :%d \n\n", row[4]
end
sth.finish
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment