JDBC connection with PostgreSQL database


In this tutorial we will learn JDBC connection with PostgreSQL database using PostgreSQL jar. How to register PostgreSQL driver in java- How to getConnection in java - Writing your jdbc(Java database connectivity) program to connect with PostgreSQL. In previous tutorial we configured java build path in eclipse and connected with Oracle, MsSql and MsSql databases.



(Minimum requirement is you should have Postgresql 7.2 or newer and java 6 or newer)

Hostname = localHost
Port =5432 (default port)
SID= mydb
Username =ankit
Password=PostgreSQL123

Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb",
                                                               "ankit", "PostgreSQL123");


Example/ Full program to connect to PostgreSQL database using Type 4 driver - java JDBC program >
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class PostgreSQL_JdbcConnectionSetupExample {
   public static void main(String... arg) {
          Connection con = null;
          try {
                 // registering postgresql driver class
                 Class.forName("org.postgresql.Driver");
                 // getting connection
                 con = DriverManager.getConnection(
                              "jdbc:PostgreSQL://localhost:5432/mydb",                     
                                                           "root","PostgreSQL123");
                 // Test connection is null or not
                 if (con != null)
                       System.out
                          .println("Connection established successfully with postgresql database!");
                 else
                       System.out.println("No Connection!");
          } catch (ClassNotFoundException e) {
                 e.printStackTrace();
          } catch (SQLException e) {
                 e.printStackTrace();
          } finally {
                 try {
                       if (con != null)
                              con.close(); // close connection
                 } catch (SQLException e) {
                       e.printStackTrace();
                 }
          }
   }
}
/*OUTPUT
Connection established successfully with postgresql database!
*/

Above JDBC java program will connect you to PostgreSQL  database using Type 4 java JDBC driver.

So, In this tutorial we learned JDBC connection with PostgreSQL database using  PostgreSQL jar. And registering PostgreSQL driver in java and getting PostgreSQL connection in java JDBC.


RELATED LINKS>

JDBC tutorial connection with Oracle 11g


eEdit
Must read for you :