Think about how to manipulate a database in Java requires a database driver. Of course, Ruby is no exception. Naturally, a database driver is required. I feel a little more complicated to install the database driver in Ruby than in Java.
- First, you need to copy the file libmysql. DLL to the binfile under the ruby installation directory under the bin directory of your MySQL database.
- Second, you needHttp://rubyforge.org/projects/MySQL-WinDownload a driver packageMySQL-2.7.3-mswin32.gem
- Next, we switch to the installation directory of the driver package under the command line. Run gem installMySQL-2.7.3-mswin32.gem. OK driver installation is complete
- Finally, we need to mount MySQL under/lib/Ruby/gems/1.8/gems/mysql-2.7.3-x86-mswin32/EXT In the ruby installation directory. so files are copied to the/lib/Ruby/site_ruby/1.8/i386-msvcrt file under the ruby installation directory.
All right, everything is ready. We want to start writingCodeThe content of the test. RB file is as follows:
Require 'mysql' <br/> begin <br/> puts "connect to MySQL Database" <br/> DBH = MySQL. real_connect ("localhost", "root", "root", "chj", 3306) # connect to the local database: User name: Root Password: root database: chj Port: 3306 <br/> puts "Connect success" <br/> puts "================" <br/> # DBH. query ("Drop table if exists member") <br/> # DBH. query ("create table member (memberid int, email varchar (25), aliww varchar (30)") <br/> # DBH. query ("insert Into Member values (1, 'abc @ 163.com, 'zhangsan') ") <br/> # printf" % d rows were inserted/N ", DBH. affected_rows <br/> res = DBH. query ("select memberid, email, aliww from member") <br/> while ROW = res. fetch_row DO <br/> puts "# {row [0] }|#{ row [1] }|#{ row [2]}" <br/> end <br/> rescue MYSQL:: Error => E <br/> puts "error code: # {e. errno} "<br/> puts" error message: # {e. error} "<br/> puts" error sqlstate: # {e. sqlst Ate} "if E. respond_to? ("Sqlstate") <br/> ensure <br/> DBH. Close if DBH <br/> puts "Close the connection" <br/> end
Run:
Ruby test. Rb
Experience Ruby in 20 minutes
Http://www.ruby-lang.org/zh_cn/documentation/quickstart/