Skip to content

Instantly share code, notes, and snippets.

Created July 24, 2009 17:57
Show Gist options
  • Save anonymous/154446 to your computer and use it in GitHub Desktop.
Save anonymous/154446 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
#Do nothing!
end
end
def disconnect
if self.db_type == 'sql_server'
self.cnnxn.disconnect
elsif self.db_type == 'mysql'
self.cnnxn.close
else
#Do nothing!
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
#Do nothing!
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
return results.to_s
elsif results.length > 1 || (results.length == 1 && results[0].length > 1)
return results
else
#Do nothing!
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
return results.fetch.to_s
elsif results.num_rows > 1 || results.field_count > 1
output = []
results.each do |row|
output << row
end
return output
else
#Do nothing!
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment