Skip to content

Instantly share code, notes, and snippets.

@kminiatures
Created September 25, 2014 04:55
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 kminiatures/5d3ef5f678dfc862a145 to your computer and use it in GitHub Desktop.
Save kminiatures/5d3ef5f678dfc862a145 to your computer and use it in GitHub Desktop.
small mysql exec
class MySQL
def initialize(database)
@database = database.to_s
end
def exec(sql)
if sql =~ /\.sql$/ and File.exists? sql
sql = File.read(sql, encoding: Encoding::UTF_8)
end
rows = []
# user and password are included in my.cnf
cmd = %{mysql --defaults-extra-file=my.cnf #{@database} -e "#{sql} \\G"}
`#{cmd}`.strip.split(/\*\*\*\*\*.*/).each do |result|
next if result == ''
h = {}
result.strip.split("\n").each do |line|
column, value = line.split(":")
h[column.strip.to_sym] = value.strip
end
rows << h
end
rows
end
end
@kminiatures
Copy link
Author

MySQL.new("foo").exec("select id,name from users").each do|u|
  puts u['name']
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment