0

我将 Rails 连接到外部 MSSQL 数据库。在 database.yml 中,适配器是 sqlserver。

查询代码:

class External < ActiveRecord::Base
   def self.select_all_entries
      external_connection_hash = configurations["external_DB"]
      establish_connection external_connection_hash
      con = connection()

      side = con.execute("Select * from dbo.BBOrders").fetch_row;
      return side
   end
end

我得到错误 - -1:Fixnum 的未定义方法“fetch_row”

数据库信息正确。我试图访问另一个表并得到相同的答案,但如果我访问一个没有条目的表,它会引发另一个异常,所以它正在连接但没有给出值。有任何想法吗?

编辑数据库.yml

development:
  adapter: sqlserver
  dsn: K_Connection
  #dsn: mydsn
  mode: odbc
  #mode: dblib
  encoding: utf8
  database: KTrade
  host: xxx.xxx.xxx.xxx
  username: tr
  password: tr2
4

2 回答 2

0

我认为你需要一颗宝石。DBI ODBC Drive 可能是众多可用选项之一。但请尝试此 URL ( http://www.easysoft.com/developer/languages/ruby/rails.html#introduction )上的说明

最终结果将如下所示

require 'dbi' # Replace MY_DSN with the name of your ODBC data # source. Replace and dbusername with dbpassword with # your database login name and password. DBI.connect('dbi:ODBC:MY_DSN', 'dbusername', 'dbpassword') do | dbh | # Replace mytable with the name of a table in your database. dbh.select_all('select * from mytable') do | row | p row end end

于 2013-06-12T19:44:26.743 回答
0

您无需设置 Model 类即可建立数据库连接。

在 database.yml 中定义您的数据库,去掉 External 类,ActiveRecord::Base 将在您加载 rails 时建立连接(使用 rails s 或 rails c)

在 database.yml 中,您告诉活动记录您正在使用 sqlserver 适配器,这意味着您的 Gemfile 中应该有这个 gem:https ://github.com/rails-sqlserver/activerecord-sqlserver-adapter

在 Rails 中定义模型类的惯例是将其定义为资源。您有一个名为 dbo.BBorders 的表名。有点奇怪的名字,它可能应该只是“bb_orders”或“orders”。那么您的型号名称是:

class BbOrder < ActiveRecord::Base
  #pay attention to capitalization and singularity/plurality
  #convention is for table name be the plural, camel cased version of the model name
  #BbOrder is the model name. bb_orders is the table name
end

或者

class Order < ActiveRecord::Base
end

如果您的表名必须是“dbo.BBOrders”,那么您可以覆盖 Rails 期望的默认表名:

class BbOrder < ActiveRecord::Base
  self.table_name = "dbo.BBOrders"
end

一旦你定义了一个模型并与一个表关联,你可以从控制台查询它:

BbOrder.all

ActiveRecord will generate the query:
"select * from bb_orders" (or whatever the table name is)

如果您真的想编写自定义查询,您可以使用:

BbOrder.connection.execute("<whatever arbitrary sql you want")

如果您尝试“获取一行”,那么您必须向它提供有关您尝试获取的行的一些信息:

BbOrder.find(45)
will generate:
"select bb_orders.* from bb_orders where id = 45"
and this will return an instance of your BbOrder class.

或更复杂的东西:

BbOrder.where(:shipped => true)
will generate:
"select bb_orders.* from bb_orders where shipped"
and this will return collection of BbOrder instances where the attribute shipped is true
in other words, a row in the database where the shipped column is true 
corresponds to one BbOrder instance
于 2013-06-12T19:29:23.260 回答