使用ruby与MS Access数据库交互
ruby常规访问access数据库的方法应该是使用DBI库
:
require 'dbi'
DBI.connect("DBI:ADO:Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb;")
可是
简单尝试之后没能成功,提示找不到驱动器ADO,懒得再试,遂找其他方法。
一番搜索之后,发现可以用WIN32OLE来访问access,写一个简单的类包装之:
require 'win32ole'
class AccessDb
attr_accessor :mdb, :connection, :data, :fields
def initialize(mdb=nil)
@mdb = mdb
@connection = nil
@data = nil
@fields = nil
end
def open
connection_string = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='
connection_string << @mdb
@connection = WIN32OLE.new('ADODB.Connection')
@connection.Open(connection_string)
end
def query(sql)
recordset = WIN32OLE.new('ADODB.Recordset')
recordset.Open(sql, @connection)
@fields = []
recordset.Fields.each do |field|
@fields << field.Name
end
begin
@data = recordset.GetRows.transpose
rescue
@data = []
end
recordset.Close
end
def execute(sql)
@connection.Execute(sql)
end
def close
@connection.Close
end
end
使用方法如下:
db=AccessDb.new('f:\db.mdb')
db.open
db.query('select * from foods')
db.fields
db.data
db.execute("insert into foods values (3,'xxx',299,'xo','good!');"
db.close
下面再给出使用ruby压缩修复access数据库的例子:
require 'win32ole'
def fixaccess(path,newpath)
jet=WIN32OLE.new('JRO.JetEngine')
File.delete(newpath) if File.exist?(newpath)
sp="Provider=Microsoft.ACE.OLEDB.12.0"
ss=sp+";Data Source="+path
sd=sp+";Data Source="+newpath+";Jet OLEDB:Engine Type=5"
jet.CompactDatabase ss,sd
end
比如要求压缩db.mdb文件,压缩后的文件名为new_db.mdb操作如下:
fixaccess('f:\db.mdb','f:\new_db.mdb')
方法fixaccess中的sp在安装了office2007的系统上
相关文档:
class Point
@x = 1
@y = 2
def initialize(x,y)
@x,@y = x,y
end
end
代码中的@x,@y为实例变量,实例变量只对self的环境起作用,因此initialize外面的@x=1,@y=2只对类本身起作用,而方法内部,的@x,@y是对对象的实例起作用的。
class Point
include Enumerable
def initialize(x ......
我们知道ruby中对于整数的[],[]=,<<,>>操作是针对于二进制的值来运算的。
我现在写一个针对十进制数操作的类,拥有整数的所有方法,如下:
class InterEx
def initialize(val=0)
@val=val
end
def to_s
@val.to_s
end
def [](idx)
self.to_s[idx].to_i
end
d ......
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Str
{
public partial class Form1 : F ......
开发环境:
Ruby:1.9.1
Rails:2.3.5
Rake:0.8.7
Rack:1.0.1
Mysql:5.0.9
Ruby-mysql:mysql-2.8.1-x86-mswin
IDE:RubyMine2.0.1
数据库准备:
database:dbdevelopment
user:crystal
password:crystal
一、创建Ruby项目RorTest
二、修改database.yml
这里只启用development环境数据库,修改配置文件如下:
dev ......
前言
在《Routing的载入》中,我大致介绍了一下Rails中最简单的route是如何加载的。这篇文章,我将来讲一讲Rails系统中更为复杂的named route和与RESTful相关的resource是如何被加载的。为了不重复太多的笔墨,这篇文章将在前文的基础上进行,如果发现单独看此文时,有少许云里雾里,建议先看一看我的前篇文章:R ......