Mistři v programování na #hovnokod

Ruby #279

#!/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

HovnoKod,