< Return to Blog

Easily Create MySQL Databases with Ruby!

Here's a simple script to create those pesky mysql databases quite easily

require 'mysql2'

@db_host = 'localhost'
@login_user = 'root'

STDOUT.sync = true
puts "Enter password for mysql root user:"
@login_pass = gets.chomp
puts "\nDatabase name:"
@db_name = gets.chomp
puts "\nDatabase username:"
@db_user = gets.chomp
puts "\nDatabase user password:"
@db_pass = gets.chomp

client = Mysql2::Client.new(:host => @db_host,
                            :username => @login_user,
                            :password => @login_pass)
client.query("CREATE DATABASE #{@db_name} CHARACTER SET utf8")
client.query("GRANT USAGE ON *.* TO #{@db_user}@#{@db_host} IDENTIFIED BY '#{@db_pass}'")
client.query("GRANT ALL PRIVILEGES ON #{@db_name}.* TO #{@db_user}@#{@db_host}")
client.query("FLUSH PRIVILEGES")

Checkout the gist for a modified version that also sets up the test database as well!