我们在使用Ruby语言的时候,经常会遇到与数据库相关的知识。在这里我们将会学到一些常见的Ruby连接数据库的一些技巧讲解。#t#
Ruby连接数据库1 连接SQLite:
- require 'sqlite'
- db = SQLite::Database.new
("library.db") - db.execute("select title,
author from books") do |row| - p row
- end
- db.close
Ruby连接数据库2连接mysql:
- require 'mysql'
- m = Mysql.new("localhost",
"name","password","maillist") - r = m.query("SELECT * FROM people ORDER BY name")
- r.each_hash do |f|
- print "#{f['name']} - #{f['email']}"
- end
Ruby连接数据库3连接到PostgreSQL:
- require 'postgres'
- conn = PGconn.connect
("",5432, "", "", "testdb")- conn.exec("create table rtest
( number integer default 0 );")- conn.exec("insert into rtest
values ( 99 )")- res = conn.query("select * from rtest")
- # res id [["99"]]