Skip to content

Instantly share code, notes, and snippets.

@kilaulena
Last active December 31, 2015 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kilaulena/8006679 to your computer and use it in GitHub Desktop.
Save kilaulena/8006679 to your computer and use it in GitHub Desktop.
hello world in mysql
# encoding: UTF-8
# based on http://zetcode.com/db/mysqlrubytutorial/
#
# gem install mysql2
require 'mysql'
begin
con = Mysql.new 'localhost', 'root', ''
# con.query("create database miau;")
all_dbs = con.list_dbs
all_dbs.each do |db|
puts db
end
puts "----"
con.query("use miau;")
con.query("CREATE TABLE IF NOT EXISTS \
Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
con.query("CREATE TABLE IF NOT EXISTS \
Countries(Id INT PRIMARY KEY AUTO_INCREMENT, Capital VARCHAR(25))")
result = con.query("show tables;")
puts "#{result.num_rows} tables in the db."
result.num_rows.times do
puts result.fetch_row.join("\s")
end
con.query("INSERT INTO Writers(Name) VALUES('Jack London')")
con.query("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
con.query("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
con.query("INSERT INTO Writers(Name) VALUES('Emile Zola')")
con.query("INSERT INTO Writers(Name) VALUES('Truman Capote')")
result = con.query("SELECT * FROM Writers;")
result.num_rows.times do
puts result.fetch_row.join("\s")
end
rescue Mysql::Error => e
puts e.errno
puts e.error
ensure
con.close if con
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment