This post demonstrates how to connect to MySQL from Ruby, insert, select and delete table rows.
Installation Details
These are the stuff currently installed on my Windows 10 box.
- Notepad++
- Ruby
- ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32]
- Gem 2.6.7
- mysql2 (install gem using the command below)1gem install mysql2
For more information on mysql2, visit https://github.com/brianmario/mysql2 - eventmachine (install gem using the command below)1gem install eventmachine
Install the gems
MySQL Server Details
You will be connecting to a MySQL Server and therefore it has to be installed first. Then, create a database schema rubydb.
Database Table
Create a database table persons using the following SQL DDL
1 2 3 4 | CREATE TABLE `rubydb`.`persons` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NULL, PRIMARY KEY (`id`)); |
Our Ruby Codes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | require "mysql2/em" @db_host = "localhost" @db_user = "root" @db_pass = "whatever" @db_name = "rubydb" client = Mysql2::Client.new(:host => @db_host , :username => @db_user, :password => @db_pass, :database =>@db_name) # We insert some data using MySQL multi-row insert client.query("insert into persons(name) values('Mark'), ('Osman'), ('Conan')") # Retrieve all rows from the persons table results = client.query("SELECT * FROM Persons") # Display all fields results.each do |row| puts row["id"].to_s() + "|" + row["name"] end # Clear the table client.query("delete from persons") |
Run the script
To run the script from the command-line, use the following command.
1 | ruby r2mysql.rb |
Output