Created
January 18, 2011 16:02
-
-
Save dtolj/784634 to your computer and use it in GitHub Desktop.
Ruby MS access create database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# | |
# | |
# | |
# | |
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 | |
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
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.