env: ubuntu
首先需要安装 mysql dev library
sudo apt-get install libmysqlclient15-dev
不然直接sudo gem install mysql会报错:
l-config=/usr/local/mysql/bin/mysql_config
Building native extensions. This could take a while...
ERROR: Error installing mysql:
ERROR: Failed to build gem native extension.
/usr/bin/ruby1.8 extconf.rb --with-mysql-config=/usr/local/mysql/bin/mysql_config
extconf.rb:10: command not found: /usr/local/mysql/bin/mysql_config --cflags
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
...
Building native extensions. This could take a while...
ERROR: Error installing mysql:
ERROR: Failed to build gem native extension.
/usr/bin/ruby1.8 extconf.rb --with-mysql-config=/usr/local/mysql/bin/mysql_config
extconf.rb:10: command not found: /usr/local/mysql/bin/mysql_config --cflags
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
...
然后:
sudo gem install mysql
如果你是通过sudo apt-get install ruby安装的ruby,那么可能开始会出现以下错误是:
`require': no such file to load -- mkmf (LoadError)
使用
sudo apt-get install ruby1.8-dev
安装ruby可以避免这个问题。
然后写一段代码看看是否已经ok了:
require 'rubygems'
require 'mysql'
def with_db
dbh = Mysql.real_connect('localhost','root','xxxxxx','deal')
begin
yield dbh
ensure
dbh.close
end
end
with_db do |db|
res = db.query('select * from route limit 2')
res.each{ |row| row.each{|field| puts field } }
res.free
end