Created
May 30, 2011 02:07
-
-
Save brianstorti/998361 to your computer and use it in GitHub Desktop.
DBI example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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