1、安装Mysql
我这里装的mysql5.5
2、复制 MySQL\MySQL Server 5.5\lib\libmysql.dll 到ruby/bin 目录
3、安装 mysql-mingw32.gem
F:\Ruby>gem install mysql
Fetching: mysql-2.8.1-x86-mingw32.gem (100%)
Successfully installed mysql-2.8.1-x86-mingw32
1 gem installed
Installing ri documentation for mysql-2.8.1-x86-mingw32...
Installing RDoc documentation for mysql-2.8.1-x86-mingw32...
4、测试
require 'mysql'
begin
db = Mysql.init
db.options(Mysql::SET_CHARSET_NAME, 'utf8')
db = Mysql.real_connect("127.0.0.1", "dbuser", "dbuser", "test", 3306)
db.query("SET NAMES utf8")
db.query("drop table if exists tb_test")
db.query("create table tb_test (id int,text LONGTEXT) ENGINE=MyISAM DEFAULT CHARSET=utf8")
db.query("insert into tb_test (id, text) values (1,'first line'),(2,'second line')")
printf "%d rows were inserted\n",db.affected_rows
rslt = db.query("select text from tb_test")
while row = rslt.fetch_row do
puts row[0]
end
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
db.close if db
end
5、查看运行结果
F:\Ruby>ruby testDB.rb
2 rows were inserted
first line
second line
F:\Ruby>
数据库中会看到在test库下新建了tb_test 表,表里插入了两条数据。