Skip to main content

How to connect to CSV files using Ruby DBI ODBC and no DSN

I had a hard time finding a way of connecting to csv files using ruby's dbi through the odbc driver without using a DSN. The odbc turned not to work with Microsoft Text driver for odbc because the name of the driver has a semicolon in it. Thus, the ruby code fro the driver was splitting the name of driver, resulting in a keyword syntax error. The following is the (working) code that shows how to connect to csv files using dbi and odbc, note that I had to override require to add the fix to the odbc driver because dbi loads the driver using require:
require "dbi"   

alias :old_require :require 

def require(library)
  old_require(library)
  if library.downcase.include?("odbc")
    define_odbc_fix()
  end
end

def define_odbc_fix
  DBI.class_eval <<-'THERE'
 
  module DBD
    module ODBC
      class Driver < DBI::BaseDriver
        #JPT: fixed to allow the ";" character in the connection string.
        # Obeys the rule of "If a semicolon (;) is part of a value it must be delimited by quotation marks (")"
        # quoted from http://connectionstrings.com/default.aspx?article=what_rules_apply_to_connection_strings
        def connect(dbname, user, auth, attr)
    
        colon_stuffing_string = "@WACKYsUFF@"
          dbname.gsub!('";"', colon_stuffing_string)
          driver_attrs = dbname.split(';')

          if driver_attrs.size > 1
            # DNS-less connection
            drv = ::ODBC::Driver.new
            drv.name = 'Driver1'
            driver_attrs.each do |param|
              param.gsub!(colon_stuffing_string, ";")
              pv = param.split('=')
              next if pv.size < 2
              drv.attrs[pv[0]] = pv[1]
            end
            db = ::ODBC::Database.new
            handle = db.drvconnect(drv)
          else
            # DNS given
            handle = ::ODBC.connect(dbname, user, auth)
          end

          return Database.new(handle, attr)
        rescue ODBCErr => err
          raise DBI::DatabaseError.new(err.message)
        end
      end
    end
  end
  THERE

end

begin
  conn_str = "DBI:ODBC:Driver={Microsoft Text Driver (*.txt\";\" *.csv)};Dbq=$$path_to_folder_with_csvs$$;Extensions=csv;"
  conn_str.gsub!('$$path_to_folder_with_csvs$$', File.expand_path(".\\spreadsheets\\simple"))
  dbh = DBI.connect(conn_str, "", "")
  
  row = dbh.select_one("SELECT * from this_year_trancripts.csv")
  puts row.to_s
rescue DBI::DatabaseError => e
  puts "An error occurred"
  puts "Error code: #{e.err}"
  puts "Error message: #{e.errstr}"
ensure
  # disconnect from server
  dbh.disconnect if dbh
end

Comments

Popular posts from this blog

Mail labels and letter templates for jasperreports

The following are free (MIT license) mailing labels and letter templates for jasperreports that you can download and use in jasperserver and/or ireport: Update 3/15/2011 : I moved the Mail templates zip file here . Please consider making a small donation if the templates are of help to you, Thank you! If you need more information on how to use those templates please leave a comment in the blog.

How to create online multiplayer HTML5 games in Contruct2

  Construct2 can use websockets to send and receive messages between games. By using socket-io , we can use a Node.js script as the server and my modification to the socket-io plugin for Construct2 to allow the games to synchronize data between them in real-time. There are two parts to this design: the Node.js server and the Construct2 clients (the games playing). The main part of building an online multiplayer HTML5 game is to plan: how the clients will communicate how often and what to communicate how much of the logic will go into the server and how much to the client. In my sample game, I chose to have each client own a player and have the server just relay messages: Use string messages in the form TypeOfMessage, Parameter1, Paremeter2, Parater3, etc to communicate. Have the clients send their player position about 16 times a second. Whenever their player shoots, the client needs to send a message immediately. Almost all of the game logic will...

Send Email from C# using Outlook's COM late binding

The following sample code shows how to send emails from Outlook and Exchange using C#. This code works with any version of Outlook because it uses Late Binding to automate Outlook. Parts of the code where taken from other websites. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Threading; namespace LateBindingTest { class OutlookEmailerLateBinding { private object oApp; private object oNameSpace; private object oOutboxFolder; public OutlookEmailerLateBinding() { Type outlook_app_type; object[] parameter = new object[1]; //Get the excel object outlook_app_type = Type.GetTypeFromProgID("Outlook.Application"); //Create instance of excel oApp = Activator.CreateInstance(outlook_app_type); //Set the parameter which u want to set parameter[0] = "MAPI...