Ruby實踐—串連Mysql

來源:互聯網
上載者:User

安裝環境:

OS:Windows XP

Ruby: Ruby1.9.1

Mysql: Mysql5.1.46 (username/password: root/root  port:3306)

Ruby-Mysql Driver: mysql-2.8.1-x86-mswin32.gem

(註:用2.7.3版本的驅動在測試時會出現 require"mysql",找不到指定模組 錯誤)

IDE:RubyMine2.0.1

 

安裝Ruby,RubyMine,Mysql的事項在這裡就不多說了,提一下安裝驅動的步驟

1)在Mysql安裝目錄的 bin 目錄下,找到 ibmySQL.dll ,將該檔案複製到 Ruby 安裝目錄的 bin 目錄中

2)http://rubyforge.org/frs/?group_id=1598,下載 mysql-2.8.1-x86-mswin32.gem,這是 mysql_Ruby驅動程式。

       命令列,進入該檔案所在目錄,運行 gem install mysql-2.8.1-x86-mswin32.gem ,安裝成功即可。

     

 

建立Ruby測試類別

MysqlTest.rb

class MysqlTest<br /> #Code here<br /> require "mysql"<br /> def testMysql<br /> dbc=Mysql.real_connect('localhost','root','root','mysql')<br /> res=dbc.query('select * from user')<br /> puts "Test Mysql...."<br /> while row=res.fetch_row do<br /> puts "#{row[0]}"<br /> end<br /> end<br /> def createTable<br /> dbc=Mysql.real_connect('localhost','root','root','test')<br /> dbc.query("drop table if exists cux_users")<br /> dbc.query("create table cux_users(id int,name char(20))")<br /> dbc.query("insert into cux_users values(1,'Tom')")<br /> printf "Create Table........"<br /> printf "%d rows were inserted/n",dbc.affected_rows<br /> res = dbc.query("SELECT name FROM cux_users")<br /> puts "===Select Data===/n"<br /> while row = res.fetch_row do<br /> printf "%s, %s/n", row[0], row[1]<br /> end<br /> puts "==================/n"<br /> puts "Server version: " + dbc.get_server_info<br /> rescue Mysql::Error => e<br /> puts "Error code: #{e.errno}"<br /> puts "Error message: #{e.error}"<br /> puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")<br /> ensure<br /> puts "Close Connection......."<br /> dbc.close if dbc<br /> end<br /> (MysqlTest.new).testMysql<br /> (MysqlTest.new).createTable<br />end

 

測試結果:

C:/Ruby19/bin/ruby.exe -e STDOUT.sync=true;STDERR.sync=true;load($0=ARGV.shift) E:/Ruby/Test/com.crystal/mysql_test.rb
Test Mysql....
localhost
Create Table........1 rows were inserted
===Select Data===
Tom,
==================
Server version: 5.1.46-community
Close Connection.......

Process finished with exit code 0

 

查看資料庫test

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.