使用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的系统上
相关文档:
在ASP.NET中调用EXCEL组件的时候,如果没有配置DCOM中EXCEL权限问题,结果程序会报:Access is denied.
解决的方法有两种:
第一种,在web.config中设置一个节点.
<identity impersonate="true" />
不过这种方法只能解决local电脑上的Excel Access is denied的问题
如果是服务器的话,有客户机访问页面的时候, ......
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 ......
安装环境:
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的事项在这里就不多 ......
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 ......