ruby连接mysql数据库

以下操作在ubuntu下进行

前提要安装好ruby-mysql

gem install ruby-mysql
require 'rubygems'
require 'mysql'
begin
  db = Mysql.new('localhost', 'username', 'password', 'password')
  puts "connected"
rescue Mysql::Error
  puts "Oh noes! We could not connect to your database. -_-;;"
  exit 1
end

begin
  results = db.query "select * from blog.wp_users;"
  puts "blog has #{results.num_rows} users."
  puts results.class
  results.each do |row|
    puts row.join(" |  ")
  end
  results.free
ensure
  db.close
end

结果将打印出wp_users这张表中的内容。

发表评论

电子邮件地址不会被公开。 必填项已用*标注