Skip to content

Instantly share code, notes, and snippets.

@ecleel
Forked from dtolj/gist:784634
Created February 8, 2012 05:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ecleel/1765587 to your computer and use it in GitHub Desktop.
Save ecleel/1765587 to your computer and use it in GitHub Desktop.
Ruby MS Access adapter
require 'rubygems'
require 'win32ole'
require 'csv'
mdb_file="c:/Sites/labs/50q.bok"
class AccessDb
attr_accessor :mdb, :connection, :data, :fields, :catalog
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
@connection = WIN32OLE.new('ADODB.Connection')
@connection.Open(connection_string)
@catalog = WIN32OLE.new("ADOX.Catalog")
@catalog.ActiveConnection = @connection
# catalog.create(connection_string)
# Source="#{@mdb_file}"
end
def query(sql)
recordset = WIN32OLE.new('ADODB.Recordset')
puts recordset.ole_methods
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 tables
tables = []
@catalog.tables.each {|t| tables << t.name if t.type == "TABLE" }
tables
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
# db.query("Select * from b1611")
# puts db.connection.invoke "OpenSchema" , "b1611"
puts db.tables
# puts db.fields
# puts db.data
# puts db.execute "select * from tables"
# db.close
@vhochstein
Copy link

I m trying to implement a sql injection safe way to perform inserts:
sql = "INSERT INTO tblTest ([myName], [integerNumber], [isRed]) VALUES(?, ?, ?);"

ocmd = WIN32OLE.new('ADODB.Command')
ocmd.CommandType = 1
ocmd.ActiveConnection = @connection
ocmd.CommandText = sql

values.each_with_index do |value, index|
ocmd.Parameters.Item(index).Value = value
end

Unfortunetly, that fails if value is nil.

Do you know how I may pass a nil value to a parameter?

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