1

所以我可以将这个 gem 用于活动记录:https ://github.com/jruby/activerecord-jdbc-adapter

但是,我想在 JRuby 上使用以下代码连接到旧数据库并运行一些手动查询,我该如何使用 JRuby / Rails 4.0.0?

require 'pg'
conn = PGconn.connect("192.168.0.2", 5432, '', '', "mydb", "postgres", "password")
4

2 回答 2

1

文档提出了以下建议:

# connection setup
ActiveRecord::Base.establish_connection(
  :adapter => 'jdbc',
  :driver => 'org.postgresql.Driver',
  :url => 'jdbc:postgresql:sample_db;create=true'
)

或者

ActiveRecord::Base.establish_connection(
  adapter: 'postgresql',
  database: 'db/my-database'
)

这是假设您使用 JDBC 和适当的配置。为此,我建议查看Postgres 的文档

那里提供的示例是用 Java 编写的:

String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","fred");
props.setProperty("password","secret");
props.setProperty("ssl","true");
Connection conn = DriverManager.getConnection(url, props);

String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";
Connection conn = DriverManager.getConnection(url);

...但我会沿着这些思路推出一些东西:

ActiveRecord::Base.establish_connection(
  :adapter => 'jdbc',
  :driver => 'org.postgresql.Driver',
  :url => 'jdbc:postgresql:sample_db;create=true'
  :user => 'myuser'
  :password => 's3cret!'
)

或者,还有JRuby-PG

问候,

于 2013-09-13T04:37:35.120 回答
0

所以这里的例子有效..

https://github.com/jruby/jruby/wiki/JDBC

def vegetableFinder(vegetable)
  # This function takes a hashmap of vegetables and attempts to
   # find them from our grocery database. For each item found, we
  # call our 'makevegetablesoup' function.

  # Load all required gems
  require "rubygems"
  require "jdbc/mysql"
  require "java"

  begin
    # Prep the connection
    Java::com.mysql.jdbc.Driver
    userurl = "jdbc:mysql://HOST/DATABASE"
    connSelect = java.sql.DriverManager.get_connection(userurl, "USERNAME", "PASSWORD")
    stmtSelect = connSelect.create_statement

# Define the query
selectquery = %q{SELECT name, type, size, price
      FROM vegetables
      WHERE type = "#{vegetable["type"]}"
      AND size = "#{vegetable["size"]}}

# Execute the query
rsS = stmtSelect.execute_query(selectquery)

# For each row returned do some stuff
while (rsS.next) do
  veg = Hash.new
  veg["vegname"] = rsS.getObject("name")
  veg["vegtype"] = rsS.getObject("type")
  veg["vegprice"] = rsS.getObject("size")
  veg["vegsize"] = rsS.getObject("price")
  makevegetablesoup(veg)
end
  end
  # Close off the connection
  stmtSelect.close
   connSelect.close
   return truth
end
于 2013-09-15T11:13:48.563 回答