Skip to content

Instantly share code, notes, and snippets.

@dtolj
Created January 18, 2011 16:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dtolj/784634 to your computer and use it in GitHub Desktop.
Save dtolj/784634 to your computer and use it in GitHub Desktop.
Ruby MS access create database
#
#
#
#
#
require 'rubygems'
require 'win32ole'
require 'csv'
mdb_file="c:/dtolj/ruby_projects/phone.accdb"
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='
#Access 2010 connection string
connection_string = 'Provider=Microsoft.ACE.OLEDB.12.0;Data Source='
connection_string << @mdb
#create connection
@connection = WIN32OLE.new('ADODB.Connection')
@connection.Open(connection_string)
#Create new database
cat = WIN32OLE.new("ADOX.Catalog")
cat.ActiveConnection = @connection
#catalog.create(connection_string)
#Source="#{@mdb_file}"
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
#create empty ms access file
file = File.open(mdb_file, File::RDWR|File::CREAT)
db = AccessDb.new(mdb_file)
db.open
@dtolj
Copy link
Author

dtolj commented Jan 18, 2011

ruby_access.rb:32:in method_missing': (in OLE methodOpen': ) (WIN32OLERuntime
Error)
OLE error code:80004005 in Microsoft JET Database Engine
Unrecognized database format 'c:\dtolj\ruby_projects\phone.accdb'.
HRESULT error code:0x80020009
Exception occurred.
from ruby_access.rb:32:in open' from ruby_access.rb:77:in

'

@jmozmoz
Copy link

jmozmoz commented Jun 7, 2011

Have you tried the solutions from this link:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/81808

The method based on win32ole still works, the version with the ODBC gem seems broken now.

@ipstone
Copy link

ipstone commented Mar 8, 2013

change the connect to this: connection.Open('Provider=Microsoft.ACE.OLEDB.12.0; ...
it works on my windows xp/access2007

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment