Think before you speak, read before you think.

ruby连接mysql数据库

by

in

以下操作在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这张表中的内容。


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *