Friday, 25 January 2013

Connection of Java program with PostgreSql database

Connection of Java program with PostgreSql database

For connecting a Java program to PostgreSql, we need the following software :
1) Jdk (any version)
2) PostgreSql database
3) PostgreSql Driver (postgresql-jdbc3.jar)
   
Download the  postgresql-jdbc3.jar  from the internet.

Set CLASSPATH of MySql Driver :
Set the classpath  i.e the location of  postgresql-jdbc3.jar  in the environment variable named CLASSPATH .

However the Java Program shown below creates the table student from the program itself and inserts values in it. If we don't want to create the table in the program and like to use the table student already created in database, then skip the 8th line of the program containing the create table statement.          
In the following program,
         table name = student        (table to be connected)
         username = postgres       (username is set by user during installation)
         password = postgres        (password is set by user during installation)
         database = postgres        (default database of PostgreSql)

Java Program :

import java.sql.*;
public class DBCpostgresql
{public static void main(String args[]) throws Exception
{Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres","postgres","postgres");
Statement st= con.createStatement();
int i1= st.executeUpdate("create table student(sid integer, sname text, marks integer)"); //create table
int i2=st.executeUpdate("insert into student values(7,'mayank',97)");                   //insertion of values
int i3=st.executeUpdate("insert into student values(14,'vikash',97)");                     //insertion of values
ResultSet rs = st.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getString(1)+"    "+rs.getString(2)+"    "+rs.getString(3));  //printing data on console
rs.close();
st.close();
con.close();
}
}

   
Note :  In case of database like PostgreSql, we need to download the jar file containing Driver class (postgresql-jdbc3.jar) separately and then set its classpath as it is not supplied along with the PostgreSql database software.

1 comment: