1、Windows中加工数据有时候需要借助关系数据库,而使用Ruby DBI操作MySQL是最快捷的办法;
2、mysql-2.9.1已经停止维护,随着Ruby的升级需要变更一些内容才能通过本地代码的编译;
3、下载mysql-2.9.1.gem,链接在这里https://rubygems.org/downloads/mysql-2.9.1.gem;
4、将下载的gem包解包到本地目录;
gem unpack mysql-2.9.1.gem
5、生成gemspec;
gem spec mysql-2.9.1.gem --ruby > mysql-2.9.1/mysql-2.9.1.gemspec
6、进入mysql-2.9.1目录,编辑ext\mysql_api\mysql.c文件,搜索rb_cFixnum文本串,找到1320行,将对该类型的判断注释掉:
else if (argv[i] == rb_cNumeric || argv[i] == rb_cInteger /*|| argv[i] == rb_cFixnum*/)
7、回退到初始解压的目录,重新build包;
gem build mysql-2.9.1.gemspec
8、下载编译本地代码的msql开发工具包,链接如下http://dev.mysql.com/get/Downloads/Connector-C/mysql-connector-c-noinstall-6.0.2-winx64.zip;
9、解压mysql-connector-c-noinstall-6.0.2-winx64.zip待用,拷贝下解压目标的目录,如D:\Workshop\test\mysql-connector-c-noinstall-6.0.2-winx64;
10、安装本地gem包;
gem install mysql-2.9.1.gem -- --with-mysql-dir=D:\Workshop\test\mysql-connector-c-noinstall-6.0.2-winx64
11、拷贝libmysql.dll至Ruby的bin目录下,保障DBI驱动载入时扩展代码可以找到该动态库;
12、这时就可以正式安装dbd-mysql驱动了;
gem install dbd-mysql
13、编写代码测试!
#encoding:gbk
require 'dbi'
dbh = DBI.connect('dbi:Mysql:mysql:hostname','user','pass')
dbh.execute('select host from user') do |stmt|
while row=stmt.fetch
puts row['host']
end
end
dbh.disconnect