· 10 years ago · Aug 30, 2016, 10:18 AM
1require 'mysql'
2
3class MigrationDB
4
5 def initialize domain, user_name, password, db_name
6 begin
7 @db_connection = Mysql.new(domain, user_name, password)
8 @db_name = db_name
9 rescue Exception => e
10 p "Error connecting to DB Server.."
11 end
12 create_and_use_db
13 end
14
15 def create_table table_name, columns
16 execute_query do
17 "CREATE TABLE IF NOT EXISTS #{table_name}(`#{columns.join('` TEXT,`')}` TEXT)"
18 end
19 end
20
21 def update_table table_name, key, value, id_key, id_value
22 execute_query do
23 "UPDATE #{table_name} SET `#{key}` = \"#{escape_string(value)}\""
24 end
25 end
26
27 def insert_table table_name, i_hash
28 execute_query do
29 "INSERT #{table_name}(`#{i_hash.keys.join('`,`')}`) VALUES(\"#{i_hash.values.map{|p| escape_string(p)}.join('","')}\")"
30 end
31 end
32
33 private
34
35 def create_and_use_db
36 execute_query do
37 "CREATE DATABASE IF NOT EXISTS #{@db_name}"
38 end
39
40 execute_query do
41 "USE #{@db_name}"
42 end
43 end
44
45 def escape_string str
46 str.gsub!(/\"/,'\'') if str.include? '"'
47 str.gsub!(/\'/,'\'') if str.include? "'"
48 str
49 end
50
51 def execute_query
52 begin
53 @db_connection.query(yield) if block_given?
54 rescue Exception => e
55 p e
56 end
57 end
58
59end
60
61# Usage:
62# connection = MigrationDB.new "localhost", "root", "", "amma"
63# connection.create_table 'tickets', ['first_name', 'last_name']
64# connection.insert_table 'tickets', {'first_name' => 'dinesh', 'last_name' => 'prabu'}
65# connection.update_table 'tickets', 'first_name', 'ramya', 'first_name', 'dinesh'