ruby连接mysql ubuntu_Ruby实践—连接Mysql

本文档详述了如何在Windows XP环境下配置Ruby 1.9.1与MySQL 5.1.46的连接。主要步骤包括复制ibmySQL.dll到Ruby的bin目录,下载并安装mysql-2.8.1-x86-mswin32.gem驱动,以及创建Ruby测试类进行数据库连接和操作。测试结果显示成功连接并执行了查询和插入操作。

安装环境:

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值