Skip to content

Instantly share code, notes, and snippets.

@dtolj
Created January 18, 2011 16:02
Show Gist options
  • 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
@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