Here's a quick post to help anyone that needs a quick JDBC Driver and URL reference when using Postgresql (Postgres) with Java (and JDBC).
The basic Postgresql JDBC Driver and URL information you need is shown here:
Postgresql (Postgres) URL (JDBC Connection) String: jdbc:postgresql://HOST/DATABASE Postgresql (Postgres) JDBC Driver String: org.postgresql.Driver
It may also help to see this used in a simple Java JDBC application. To that end, here's a simple Java JDBC Postgresql example that shows how to use the Postgres Driver and URL to establish a database connection.
public class JdbcPostgresqlDriverUrlExample
{
public static void main(String[] args)
{
Connection connection = null;
try
{
// the postgresql driver string
Class.forName("org.postgresql.Driver");
// the postgresql url
String url = "jdbc:postgresql://THE_HOST/THE_DATABASE";
// get the postgresql database connection
connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");
// now do whatever you want to do with the connection
// ...
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(2);
}
}
}
I hope that simple reference helps. There are also many other Java, JDBC, and Postgresql tutorials on this site. Just use our search form to find many other examples.
Need to be change code
When I used code - please change following line
connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");
Instead of above line write
Connection connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");
Regards
Amit Pandya
Postgres Connection code
Did you use all the code shown in the example? The Connection object reference is declared before the "try" block, and then used inside the block, so it should work fine as is.
In this small example your change makes the code more simple, but in a larger example you may want to close the connection, or return it to a connection pool, and that was part of the reason for me writing it the way I did. I think in my first example I was closing the connection in a "finally" block, but then removed it.
Either way, it should work fine, so thanks for the note.
Post new comment