Pageviews

Wednesday 22 January 2014

Java PostgreSQL Connectivity example:

by Unknown  |  in Database at  Wednesday, January 22, 2014

This tutorial covers the basics of PostgreSQL programming with Java.In this tutorial, we are going to use the PostgreSQL JDBC Driver driver.It is the official JDBC driver for PostgreSQL.

JDBC tutorial

What is PostgreSQL:



PostgreSQL is a powerful,open source object-relational database system.It is a multi-user database management system.It runs on multiple platforms including Linux, FreeBSD, Solaris, Microsoft Windows and Mac OS X.PostgreSQL is developed by the PostgreSQL Global Development Group.PostgreSQL is not controlled by any corporation or other private entity and the source code is available free of charge.

Advantages of PostgreSQL:

PostgreSQL runs on all major operating systems,including Linux,UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows. It supports text,images,sounds,and video,and includes programming interfaces for C / C++ ,Java,Perl,Python,Ruby,Tcl and Open Database Connectivity (ODBC).PostgreSQL supports a large part of the SQL standard and offers many modern features including the following:


  1. Complex SQL queries
  2. SQL Sub-selects 
  3. Foreign keys
  4. Trigger 
  5. Views
  6. Transactions
  7. Multiversion concurrency control (MVCC) 
  8. Streaming Replication (as of 9.0) 
  9. Hot Standby (as of 9.0)


Pre-requisite Softwares:

Before using PostgreSQL in our Java programs,we need to make sure that we have PostgreSQL JDBC and Java set up on our machine.

1.Download latest version of postgresql-(VERSION).jdbc.jar from postgresql-jdbc repository.

2.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.

Make sure you install the PostgreSQL,Postgre SQLJDBC driver according to your JDK versions,to check you JDK version installed on your computer,click here.


Connecting to the Database:

import java.sql.Connection;
import java.sql.DriverManager;
public class PostgreSQLJDBC { public static void main(String args[])
{
 Connection c = null;
try
{
 Class.forName("org.postgresql.Driver"); //Registering PostgreSQL JDBC Driver
c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/kanwar", "postgres", "osm"); //Here my database name is 'Kanwar' and username is 'postgres' and password is 'osm'
}
catch (Exception e)
{
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
 System.exit(0);
}
System.out.println("Opened database successfully");
}
}


This way a new Database will be created.Open your PgAdminIII and check the new database created.






0 comments:

Proudly Powered by Blogger.