Project

Profile

Help

Interact with MariaDb using Ruby

Example code

Full example code is stored at https://github.com/OSLL/mdbci/blob/integration/playground/mariadb_connection/mdb_example.rb, db dump https://github.com/OSLL/mdbci/blob/integration/playground/mariadb_connection/test_results_db.sql

Preparation

Create user

Enter mysql shell:

sudo mysql 

Enter following commands:

CREATE USER 'test_bot';
GRANT ALL PRIVILEGES ON test_results_db.* TO 'test_bot'@'%' IDENTIFIED BY 'pass';
GRANT ALL PRIVILEGES ON test_results_db.* TO 'test_bot'@'localhost' IDENTIFIED BY 'pass';
USE mysql;
SET PASSWORD FOR 'test_bot'@'%' = PASSWORD('pass');
SET PASSWORD FOR 'test_bot'@'localhost' = PASSWORD('pass');

Create db

mysql -u test_bot -ppass -e < ./playground/mariadb_connection/test_results_db.sql

Gems

sudo apt-get install ruby-dev
sudo gem install mysql2

Connecting to db

require 'mysql2'
client = Mysql2::Client.new(:host => "localhost", :username => "test_bot", :password => "pass", :database => "test_results_db")

Insert of two related entries

Executed sql (for first request):

INSERT INTO test_run (
    jenkins_id, start_time, target, box, 
    product, mariadb_version, 
    test_code_commit_id, maxscale_commit_id, 
    job_name) 
VALUES (
    1, NOW(), "target", "box", "product", 
    "mariadb_version", "test_code_commit_id", 
    "maxscale_commit_id", "job_name" );

Ruby code:

# Wrinting data
client.query('INSERT INTO test_run ('\
'jenkins_id, start_time, target, box, '\
'product, mariadb_version, test_code_commit_id, '\
'maxscale_commit_id, job_name)'\
' VALUES (1, NOW(), "target", "box", "product", '\
'"mariadb_version", "test_code_commit_id", '\
"maxscale_commit_id", "job_name" )')'

# Check last id by client field
id = client.last_id
client.query("INSERT INTO results (id, test, result) VALUES (#{id}, 'test', 1)")

Select

def printTable(tableName, client)
  puts tableName
  result = client.query("SELECT * FROM #{tableName}")
  result.each do |row|
    puts row
  end
end

Links