Saturday, 10 January 2009

Connect to PostgreSQL with JDBC driver

Here is an example to show you how to connect to PostgreSQL database with JDBC driver.

1. Download PostgreSQL JDBC Driver

Get a PostgreSQL JDBC driver at this URL : http://jdbc.postgresql.org/download.html

 

2. Java JDBC connection example

Code snippets to use JDBC to connect a PostgreSQL database

   1: Class.forName("org.postgresql.Driver");
   2: Connection connection = null;
   3: connection = DriverManager.getConnection(
   4:    "jdbc:postgresql://hostname:port/dbname","username", "password");
   5: connection.close();

See a complete example below :
File : JDBCExample.java



   1: import java.sql.DriverManager;
   2: import java.sql.Connection;
   3: import java.sql.SQLException;
   4:  
   5: public class JDBCExample {
   6:  
   7:     public static void main(String[] argv) {
   8:  
   9:         System.out.println("-------- PostgreSQL "
  10:                 + "JDBC Connection Testing ------------");
  11:  
  12:         try {
  13:  
  14:             Class.forName("org.postgresql.Driver");
  15:  
  16:         } catch (ClassNotFoundException e) {
  17:  
  18:             System.out.println("Where is your PostgreSQL JDBC Driver? "
  19:                     + "Include in your library path!");
  20:             e.printStackTrace();
  21:             return;
  22:  
  23:         }
  24:  
  25:         System.out.println("PostgreSQL JDBC Driver Registered!");
  26:  
  27:         Connection connection = null;
  28:  
  29:         try {
  30:  
  31:             connection = DriverManager.getConnection(
  32:                     "jdbc:postgresql://127.0.0.1:5432/testdb", "mkyong",
  33:                     "123456");
  34:  
  35:         } catch (SQLException e) {
  36:  
  37:             System.out.println("Connection Failed! Check output console");
  38:             e.printStackTrace();
  39:             return;
  40:  
  41:         }
  42:  
  43:         if (connection != null) {
  44:             System.out.println("You made it, take control your database now!");
  45:         } else {
  46:             System.out.println("Failed to make connection!");
  47:         }
  48:     }
  49:  
  50: }

3. Run it


Assume JDBCExample is store in c:\test folder, together with PostgreSQL JDBC driver, then run it :



   1: C:\test>java -cp c:\test\postgresql-8.3-603.jdbc4.jar;c:\test JDBCExample
   2: -------- MySQL JDBC Connection Testing ------------
   3: PostgreSQL JDBC Driver Registered!
   4: You made it, take control your database now!

Done…

0 comments:

Post a Comment