Ruby实践—连接Mysql
安装环境:
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
#Code here
require "mysql"
def testMysql
dbc=Mysql.real_connect('localhost','root','root','mysql')
res=dbc.query('select * from user')
puts "Test Mysql...."
while row=res.fetch_row do
puts "#{row[0]}"
end
end
def createTable
dbc=Mysql.real_connect('localhost','root','root','test')
dbc.query("drop table if exists cux_users")
dbc.query("create table cux_users(id int,name char(20))")
dbc.query("insert into cux_users values(1,'Tom')")
printf "Create Table........"
printf "%d rows were inserted\n",dbc.affected_rows
res = dbc.query("SELECT name from cux_users")
puts "===Select Data===\n"
while row = res.fetch_row do
printf "%s, %s\n", row[0], row[1]
end
puts "==================\n"
puts "Server version: " + dbc.get_server_info
rescue Mysql::Error => e
puts "Error code: #{e.errno}"
puts "Error message: #{e.error}"
puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
ensure
puts "Close Connection......."
dbc.close if dbc
end
(MysqlTest.new).testMysql
(MysqlTest.new).createTable
end
测试结果:
C:\Ruby19\bin\ruby.exe -e STDOUT.sync=true;
相关文档:
When I try the command "gem install thrift" with Ruby 1.9.1, I got a compilation error with something related to a C function "strlcpy()".
Then I searched the web. It seems I am not alone and the community know it.
However I do not want to wait for official update, I want to ......
历史背景[1]
诞生于1993年2月24日的Ruby(红宝石),由日本人松本行弘(Yuki Matsumoto)于1994年12月发布。 Ruby 作为一种纯面向对象的脚本程序设计语言,吸收了Smalltalk和Perl两种程序语言的特性。
Ruby理念[2]
1.首先考虑的是,减少编程时不必要的琐碎时间,令编写程序的人高兴;
2.其次是良好的界面设计;
3.强 ......
可用库:getoptlong.rs, optionparser
对应类:GetoptLong, OptionParser
前者已过时,建议使用后者,且后者比前者易用。
后者特点:
1. 参数描述和代码处理写在一起
2. 输出参数说明,不需单独维护
3. 可选参数和命令参数描述简洁
4. 参数可自动转换为特定的类
5. ......
self上下文
Ruby的self有和Java的this相似之处,但又大不相同。Java的方法都是在实例方法中引用,所以this一般都是指向当前对象的。而Ruby的代码逐行执行,所以在不同的上下文(context)self就有了不同的含义,先来看看常见的context self都代表哪些
1
2
3
4
5
6
7
8
9
10
11
12
13
......
分页中用到类变量,主要是用来标记“页码输入框”的id 如果一个页面有几个分页,“页码输入框”的id要是不同的才能分清是哪个要分页。使用类变量就是为了达到这个目的,让所有的对象实例共用一个变量,不必每次重新初始化变量。 类变量使用代码示例 1 require 'ruby-debug'
2 debugger
3 cla ......