- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
#!/usr/bin/ruby1.8
require 'mysql'
$KCODE = 'UTF8'
class Country
@@country = Array.new
@@insert_query = String.new
@@db = Mysql
def initialize(filename)
file = File.open(filename)
while !file.eof?
value, index = file.readline.split(/\s+/u)
@@country[index.to_i] = value.to_s
end
file.close
end
def database_connect
@@db = Mysql.new('localhost','username','userpass','userdatabase')
begin
@@db.query("SET NAMES utf8")
rescue
puts @@db.error
end
end
def create_query
begin
result = @@db.query("SELECT * FROM table")
rescue
puts @@db.error
end
result.each_hash do |field|
@@country.each_index do |index|
@@insert_query += "UPDATE table SET position = #{index} WHERE caption = '#{field['caption']}';" if @@country[index] == field['caption']
end
end
end
def execute_query
begin
@@insert_query.split(/;/u).each { |query| @@db.query(query) }
puts "result: #{@@db.errno}" if @@db.errno
rescue
puts @@db.error
end
end
def database_disconnect
@@db.close
end
end
cnt = Country.new('country.txt')
# connect to DB
cnt.database_connect
# construct query
cnt.create_query
# execute constructed query
cnt.execute_query
# close connect
cnt.database_disconnect