Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC- postgres, connection refused

This is my first time using java to access databases, so I probably have a simple mistake here, but when I go to retrieve my connection from a remote database I have access to, I get a connection refused.

Here's the code in question:

String url = "jdbc:postgresql:url.isformatted.like.this/database";

try {
    conn = DriverManager.getConnection(url, "username", "password");
} catch (SQLException e) {
    e.printStackTrace();
    System.exit(1);
}

(user/pass and database url removed for privacy sake)

The problem couldn't be credentials or the URL itself, as I use it to manually log in from the same box successfully using psql. I'm thinking it's probably the formatting of the URL, but I couldn't find any examples of psql being used on a remote address (they were all local host kinda things)

like image 901
RyanCacophony Avatar asked Aug 18 '09 19:08

RyanCacophony


2 Answers

According to http://www.petefreitag.com/articles/jdbc_urls/ valid urls are

jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database
jdbc:postgresql://host:port/database?user=userName&password=pass
jdbc:postgresql://host:port/database?charSet=LATIN1&compatible=7.2

Do you have the // before the host?

like image 152
atk Avatar answered Oct 04 '22 18:10

atk


I would agree with @Jonathan about having the PostgreSQL JDBC jar library on you classpath: here is what I used:

private static final String TABLE_NAME = "tablenamegoeshere";
private static final String DRIVER = "org.postgresql.Driver";
private static final String URL = "jdbc:postgresql://url.for.database/DatabaseName";
private static final String USERNAME = "yourusername";
private static final String PASSWORD = "yourpassword";


private static Connection getConnection() throws Exception {
  Class.forName(DRIVER);
  Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
  return conn;
}
like image 35
roycemathew Avatar answered Oct 04 '22 18:10

roycemathew