Installation
Before we start using PostgreSQL in our Java programs we need to make sure that we have PostgreSQL JDBC and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now let us check how to set up PostgreSQL JDBC driver.
Download latest version of postgresql-(VERSION).jdbc.jar from postgresql-jdbc repository.
Add downloaded jar file postgresql-(VERSION).jdbc.jar in your class path, or you can use it along with -classpath option as explained below in examples.
Following section assumes you have little knowledge about Java JDBC concepts. If you don't, then it is suggested to spent half and hour with JDBC Tutorial to become comfortable with concepts explained below.
Connecting To Database
Following Java code shows how to connect to an existing database. If database does not exist, then it will be created and finally a database object will be returned.
importjava.sql.Connection;importjava.sql.DriverManager;public classPostgreSQLJDBC {public static voidmain(String args[]) {
Connection c= null;try{
Class.forName("org.postgresql.Driver");
c=DriverManager
.getConnection("jdbc:postgresql://localhost:5432/testdb","postgres", "123");
}catch(Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
Before you compile and run above program, find pg_hba.conf file in your PostgreSQL installation directory and add the following line:
# IPv4 local connections:
host all all127.0.0.1/32 md5
You can start/restart postgres server in case it is not running using the following command:
[root@host]# service postgresql restart
Stopping postgresql service: [ OK ]
Starting postgresql service: [ OK ]
Now, let's compile and run above program to get connection with testdb. Here, we are using postgres as user ID and 123 as password to access the database. You can change this as per your database configuration and setup. We are also assuming current version of JDBC driver postgresql-9.2-1002.jdbc3.jar is available in the current path
C:\JavaPostgresIntegration>javac PostgreSQLJDBC.java
C:\JavaPostgresIntegration>java -cp c:\tools\postgresql-9.2-1002.jdbc3.jar;C:\JavaPostgresIntegration PostgreSQLJDBC
Open database successfully
Create a Table</