安装环境:
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
#Code here
require "mysql"
def testMysql
dbc=Mysql.real_connect('localhost','root','root','mysql')
res=dbc.query('select * from user')
puts "Test Mysql...."
while row=res.fetch_row do
puts "#{row[0]}"
end
end
def createTable
dbc=Mysql.real_connect('localhost','root','root','test')
dbc.query("drop table if exists cux_users")
dbc.query("create table cux_users(id int,name char(20))")
dbc.query("insert into cux_users values(1,'Tom')")
printf "Create Table........"
printf "%d rows were inserted/n",dbc.affected_rows
res = dbc.query("SELECT name FROM cux_users")
puts "===Select Data===/n"
while row = res.fetch_row do
printf "%s, %s/n", row[0], row[1]
end
puts "==================/n"
puts "Server version: " + dbc.get_server_info
rescue Mysql::Error => e
puts "Error code: #{e.errno}"
puts "Error message: #{e.error}"
puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
ensure
puts "Close Connection......."
dbc.close if dbc
end
(MysqlTest.new).testMysql
(MysqlTest.new).createTable
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
标签:puts,dbc,Mysql,mysql,Ruby,连接,row From: https://blog.51cto.com/u_16129500/6834668