I need access to the Postgres DB in Java within my JRuby on Rails App. Is this allowed/done. Has anyone done it?
So could I just make a singleton connection to the db via jdbc and manipulate the postgres db?
If so, please can you point me to some resources/examples that may help me this.
I have to build a feature where the Postgres DB records need to be manipulated using a Java API.
Yes, you can do this with the Java APIs in Ruby. It's difficult to provide an exact answer because I do not know what you are trying to do. But here is an example of a method that creates a connection, and manipulates the database in pseudo-JRuby
require 'java'
java_import java.net.URI
java_import java.sql.DriverManager
def do_database
connection = get_connection
stmt = connection.createStatement
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)")
stmt.executeUpdate("INSERT INTO ticks VALUES (now())")
rs = stmt.executeQuery("SELECT tick FROM ticks")
rs.next
begin
puts "Read from DB: " + rs.getTimestamp("tick")
end while rs.next
ensure
connection.close if connection != nil
end
def get_connection
dbUri = ENV["DATABASE_URL"]
username = dbUri.getUserInfo.split(":")[0]
password = dbUri.getUserInfo.split(":")[1]
port = dbUri.getPort
dbUrl = "jdbc:postgresql://#{dbUri.getHost}:#{port}#{dbUri.getPath}"
DriverManager.getConnection(dbUrl, username, password)
end