ruby和mysql连接
1 require "rubygems"
2 require "mysql"
3 def with_db
4 dbh=Mysql.real_connect('localhost','root','lovelin','lindb')
5 begin
6 yield dbh
7 ensure
8 dbh.close
9 end
10 end
11 with_db do |db|
12 db.query(%{insert into mytable values ("hello","tt")})
13 res=db.query("select * from mytable")
14 res.each { |row| puts "#{row[0]} : #{row[1]}"}
15 res.free
16 end
这是结果
goodlzp@goodlzp-desktop:~$ ruby mydb.rb
linzhipeng : M
hello : t
hello : t
hello : t
hello : t
xyx : F
hello : t
这个程序连接到mysql,插入一条数据,然后用sql显示出来。
mysql以后也要多用,太多实例程序都是用这个做的。
一直犹豫是不是要用ruby on rails,学习ruby看到太多的赞誉了。又定了一本书,很久没有这样,欲罢不能的感觉!
身未动,心已远;有多远,走多远