Ruby 使用 ODBC 连接数据库

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

require "odbc"

DSN  = "Myodbc"
USER = "YourName"
PWD  = "123"

ODBC.connect(DSN, USER, PWD) do |dbh|
  dbh.autocommit = true
  begin
    dbh.do("DROP TABLE test")
  rescue ODBC::Error; end
  dbh.do("CREATE TABLE test (id INT, name VARCHAR(30))")
  dbh.do("INSERT INTO test VALUES (?,?)", 1, 'Michael')
  dbh.autocommit = false
  dbh.prepare("INSERT INTO test VALUES(?,?)") do |sth|
    name = "AAAAA"
    99.times {|n| sth.execute(n+2, name.succ!) }
  end
  dbh.commit
  dbh.run("SELECT COUNT(*) FROM test") do |sth|
    p sth.fetch[0]  # => 100
  end
  sql = "SELECT name FROM test WHERE id BETWEEN ? AND ?"
  sth = dbh.run(sql, 49, 50)
  sth.ignorecase = true
  sth.fetch_hash do |row|
    p row['NAME']            # => "AAABW", "AAABX"
  end
  sth.drop
end