2009年5月28日

Windows 使用 Ruby 存取 mysql database

首先要安裝 Ruby http://rubyonrails.org

預設安裝目錄為 C:\ruby

使用 gem 安裝 Ruby MySQL modules

> gem install mysql
Select which gem to install for your platform (i386-mswin32)
1. mysql 2.7.3 (mswin32)
2. mysql 2.7.1 (mswin32)
3. mysql 2.7 (ruby)
4. mysql 2.6 (ruby)
5. Skip this gem
6. Cancel installation
> 1 // 選擇 1 安裝 Windows 平台 2.7.3 版
Successfully installed mysql-2.7.3-mswin32
Installing ri documentation for mysql-2.7.3-mswin32...
Installing RDoc documentation for mysql-2.7.3-mswin32...
While generating documentation for mysql-2.7.3-mswin32
... MESSAGE: Unhandled special: Special: typ...
(continuing with the rest of the installation)

寫個 ruby 程式 access mysql FileName: dbconn.rb

require "mysql"

# 取得參數
@host, @user, @pass, @db, @sql = ARGV
# 連線
m = Mysql::new(@host, @user, @pass, @db)
res = m.query(@sql)
res.each do |row|
line = ""
row.each do |c|
line = line + c + "\t"
end
puts line
end
# 關閉連線
m.close


執行測試 dbconn.rb
>ruby dbconn.rb localhost root password mysql "select * from user"

localhost root *XXXXXXX...
...

沒有留言:

網誌存檔