我目前正在使用 rails 2.3.8 和 dbi gem 来访问 mssql 数据库。生产位于交钥匙 Rails VA 中,开发位于 linux VM 中不能考虑更改为 tinytds,因为它会中断并希望使用旧方法。我目前有以下代码设置来访问和查询 mssql
外部数据.rb
def self.datapoint_connection(&block)
db_connection('type1',&block)
end
def self.db_connection(connection_type, &block)
begin
conn_data = YAML::load_file("#{Rails.root}/config/eg_databases.yml")[connection_type.to_s]
driver = conn_data.delete('driver')
user = conn_data.delete('username')
password = conn_data.delete('password')
conn_params = conn_data['entry']
conn_str = "DBI:#{driver}:#{conn_params}"
conn = DBI.connect(conn_str, user, password)
if block_given?
yield conn
else
return conn
end
ensure
# disconnect from server
conn.disconnect if conn && conn.connected? && block_given?
end
end
eg_database.yml
type1:
driver: ODBC
entry: dsn_con1
username: blah
password: 'blah'
查询另一个数据库
def excluded_testrun_users
ExternalData.datapoint_connection do |dbh|
dbh.select_all("SELECT username FROM team where team") do |row|
puts row
end
end
end
整体查询
def user_test_run_sql(granularity,date,end_date_condition=false)
"(select * from test_run where user_id NOT IN
(#{excluded_testrun_users.map{|u| DataPoint.sanitize(u)}.join(", ")})
#{' and testrun_end IS NOT NULL' if end_date_condition}) as sub_test_run"
end
我想知道这是否是在 mssql 中访问同一服务器下的多个数据库的正确方法。dsn 是否必须为每个数据库连接更改(创建)但在同一服务器下?
当我尝试跑步时。我收到以下错误
Error getting query: Unable to load driver 'ODBC' (underlying error: uninitialized constant DBI::DBD::ODBC)
.... not gonna show stupidly long called path list to every conceivable files for ruby...
/usr/local/rvm/rubies/ruby-1.8.7-p357/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/usr/local/rvm/rubies/ruby-1.8.7-p357/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
script/server:3
任何见解或帮助将不胜感激