安裝環境:
OS:Windows XP
Ruby: Ruby1.9.1
Mysql: Mysql5.1.46 (username/password: root/root port:3306)
Ruby-Mysql Driver: mysql-2.8.1-x86-mswin32.gem
(註:用2.7.3版本的驅動在測試時會出現 require"mysql",找不到指定模組 錯誤)
IDE:RubyMine2.0.1
安裝Ruby,RubyMine,Mysql的事項在這裡就不多說了,提一下安裝驅動的步驟
1)在Mysql安裝目錄的 bin 目錄下,找到 ibmySQL.dll ,將該檔案複製到 Ruby 安裝目錄的 bin 目錄中
2)http://rubyforge.org/frs/?group_id=1598,下載 mysql-2.8.1-x86-mswin32.gem,這是 mysql_Ruby驅動程式。
命令列,進入該檔案所在目錄,運行 gem install mysql-2.8.1-x86-mswin32.gem ,安裝成功即可。
建立Ruby測試類別
MysqlTest.rb
class MysqlTest<br /> #Code here<br /> require "mysql"<br /> def testMysql<br /> dbc=Mysql.real_connect('localhost','root','root','mysql')<br /> res=dbc.query('select * from user')<br /> puts "Test Mysql...."<br /> while row=res.fetch_row do<br /> puts "#{row[0]}"<br /> end<br /> end<br /> def createTable<br /> dbc=Mysql.real_connect('localhost','root','root','test')<br /> dbc.query("drop table if exists cux_users")<br /> dbc.query("create table cux_users(id int,name char(20))")<br /> dbc.query("insert into cux_users values(1,'Tom')")<br /> printf "Create Table........"<br /> printf "%d rows were inserted/n",dbc.affected_rows<br /> res = dbc.query("SELECT name FROM cux_users")<br /> puts "===Select Data===/n"<br /> while row = res.fetch_row do<br /> printf "%s, %s/n", row[0], row[1]<br /> end<br /> puts "==================/n"<br /> puts "Server version: " + dbc.get_server_info<br /> rescue Mysql::Error => e<br /> puts "Error code: #{e.errno}"<br /> puts "Error message: #{e.error}"<br /> puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")<br /> ensure<br /> puts "Close Connection......."<br /> dbc.close if dbc<br /> end<br /> (MysqlTest.new).testMysql<br /> (MysqlTest.new).createTable<br />end
測試結果:
C:/Ruby19/bin/ruby.exe -e STDOUT.sync=true;STDERR.sync=true;load($0=ARGV.shift) E:/Ruby/Test/com.crystal/mysql_test.rb
Test Mysql....
localhost
Create Table........1 rows were inserted
===Select Data===
Tom,
==================
Server version: 5.1.46-community
Close Connection.......
Process finished with exit code 0
查看資料庫test