我是 Ruby 新手,我正在尝试查询现有的 MS Access 数据库以获取报告的信息。我希望将此信息存储在 Excel 文件中。我该怎么做?
问问题
1085 次
3 回答
1
尝试其中之一:
奥莱:
require 'win32ole'
class AccessDbExample
@ado_db = nil
# Setup the DB connections
def initialize filename
@ado_db = WIN32OLE.new('ADODB.Connection')
@ado_db['Provider'] = "Microsoft.Jet.OLEDB.4.0"
@ado_db.Open(filename)
rescue Exception => e
puts "ADO failed to connect"
puts e
end
def table_to_csv table
sql = "SELECT * FROM #{table};"
results = WIN32OLE.new('ADODB.Recordset')
results.Open(sql, @ado_db)
File.open("#{table}.csv", 'w') do |file|
fields = []
results.Fields.each{|f| fields << f.Name}
file.puts fields.join(',')
results.GetRows.transpose.each do |row|
file.puts row.join(',')
end
end unless results.EOF
self
end
def cleanup
@ado_db.Close unless @ado_db.nil?
end
end
AccessDbExample.new('test.mdb').table_to_csv('colors').cleanup
ODBC:
require 'odbc'
include ODBC
class AccessDbExample
@obdc_db = nil
# Setup the DB connections
def initialize filename
drv = Driver.new
drv.name = 'AccessOdbcDriver'
drv.attrs['driver'] = 'Microsoft Access Driver (*.mdb)'
drv.attrs['dbq'] = filename
@odbc_db = Database.new.drvconnect(drv)
rescue
puts "ODBC failed to connect"
end
def table_to_csv table
sql = "SELECT * FROM #{table};"
result = @odbc_db.run(sql)
return nil if result == -1
File.open("#{table}.csv", 'w') do |file|
header_row = result.columns(true).map{|c| c.name}.join(',')
file.puts header_row
result.fetch_all.each do |row|
file.puts row.join(',')
end
end
self
end
def cleanup
@odbc_db.disconnect unless @odbc_db.nil?
end
end
AccessDbExample.new('test.mdb').table_to_csv('colors').cleanup
于 2009-10-19T19:33:31.703 回答
0
你为什么要这样做?您可以直接从 Excel 查询您的数据库。看看这个教程。
于 2009-10-15T21:12:36.287 回答