Reputation: 1117
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)
Upvotes: 5
Views: 8931
Reputation: 13
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;
}
Upvotes: 1
Reputation: 13614
I just looked ad my code which connects to a PostgreSQL database, and it looks like this:
DriverManager.getConnection(String.format("jdbc:postgresql://%s/%s", server, dbName), userName, password);
Also, make sure you're loading the PostgreSQL database driver before trying to connect:
Class.forName("org.postgresql.Driver");
and that the PostgreSQL JDBC Jar library is on your classpath.
Upvotes: 0
Reputation: 9314
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?
Upvotes: 12