0

我的问题是我想将我的连接和 SQL 语句放在课堂上的站点方法中,但是当我将它放在单独的方法中并从其他地方调用这些方法时,它不会连接到我的 MySQL 数据库。我的代码:

require 'active_record'

class Databaseoperation < ActiveRecord::Base
  def initialize
    $mysqlinfo = Hash[*File.read('/home/me/properties/mysql.property').split(/=|\n/)]
  end

  def mysqlConnect
    self.establish_connection(:adapter => 'jdbcmysql', :database => 'mydb' , :host => 'localhost', :username => 'root', :password => 'root' )
  end

  def getSqlServer
    $record = MysqlConnection.connection.select_all('SELECT * from Installation')
  end
end

dbp = Databaseoperation.new
dbp.mysqlConnect

错误信息:

ActiveRecord::ConnectionNotEstablished: ActiveRecord::ConnectionNotEstablished                                                                                                        
       retrieve_connection at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:546              
       retrieve_connection at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/connection_handling.rb:79                                        
                connection at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/connection_handling.rb:53                                         
                   columns at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/model_schema.rb:208                                               
              column_names at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/model_schema.rb:247                                               
  define_attribute_methods at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/attribute_methods.rb:29                                           
               synchronize at org/jruby/ext/thread/Mutex.java:149                                                                                                                      
  define_attribute_methods at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/attribute_methods.rb:26                                           
            method_missing at /home/me/.rvm/gems/jruby-1.7.4/gems/activerecord-4.0.0/lib/active_record/attribute_methods.rb:123                                          
              mysqlConnect at ./databaseoperation.rb:12                                                                                                                                 
                    (root) at ./databaseoperation.rb:23   

如果我不将我的语句放在我的类中的方法中,它会连接到数据库。但我真的希望能够在我的类的方法中分离连接和 sql 语句。我怎样才能做到这一点?请注意,我使用的是 jruby-1.7.4。

4

0 回答 0