Skip to content

Instantly share code, notes, and snippets.

@csexton
Forked from anonymous/gist:154446
Created July 24, 2009 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csexton/154448 to your computer and use it in GitHub Desktop.
Save csexton/154448 to your computer and use it in GitHub Desktop.
require 'DBI'
require 'mysql'
#This class is for interacting with databases. :) Handles Mysql and SQL Server.
class Database
attr_reader :db_type, :connection_string
attr_accessor :cnnxn
def initialize(conn_string,opts={})
options={:db_type => 'sql_server'}.merge(opts)
@connection_string = conn_string
@db_type = options[:db_type]
end
def connect
if self.db_type == 'sql_server'
self.cnnxn = DBI.connect "DBI:ADO:#{self.connection_string}"
elsif self.db_type == 'mysql'
a = self.connection_string.split("::")
self.cnnxn = Mysql.new(a[0],a[1],a[2])
self.cnnxn.select_db(a[3])
else
# Unknown DB Type
raise "I don't know how to handle that type of db, you jerk!"
end
self
end
def disconnect
if self.db_type == 'sql_server'
self.cnnxn.disconnect
elsif self.db_type == 'mysql'
self.cnnxn.close
else
# Unknown DB Type
raise "I don't know how to handle that type of db, you jerk!"
end
end
def query(sql)
if self.db_type == 'sql_server'
query = self.cnnxn.prepare(sql)
query.execute()
results = sexy_sql_server_results(query.fetch_all())
elsif self.db_type == 'mysql'
query = self.cnnxn.prepare(sql)
results = query.execute
results = sexy_mysql_results(results)
else
# Unknown DB Type
raise "I don't know how to handle that type of db, you jerk!"
end
end
#This method takes the results from a sql server query and converts it to a string or leaves it as an array, depending on what's returned from the query.
def sexy_sql_server_results(results)
if results.length == 1 && results[0].length == 1
results.to_s
elsif results.length > 1 || (results.length == 1 && results[0].length > 1)
results
end
end
#This method takes the results from a mysql query, which will be a MysqlStmt and converts it to either a string or an array, depending on what's returned
def sexy_mysql_results(results)
if results.num_rows == 1 and results.field_count == 1
results.fetch.to_s
elsif results.num_rows > 1 || results.field_count > 1
output = []
results.each do |row|
output << row
end
output
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment