How to connect to PostgreSQL database using a JDBC program?

JDBCJava 8Object Oriented ProgrammingProgrammingPostgreSQL

PostgreSQL is an open source relational database management system (DBMS) developed by a worldwide team of volunteers. PostgreSQL is not controlled by any corporation or other private entity and the source code is available free of charge.

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

  • Download the latest version of postgresql- from postgresql-jdbc repository.

  • Add downloaded jar file postgresql-(VERSION).jdbc.jar in your class path.

Example

Following JDBC program establishes connection to PostgreSQL database and creates a table in it.

import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class PostgreSQLJDBC {
   public static void main( String args[] ) {
      Connection c = null;
      Statement stmt = null;
      try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123");
         System.out.println("Connection established successfully");
         stmt = c.createStatement();
         String sql = "CREATE TABLE COMPANY " +
            "(ID INT PRIMARY KEY NOT NULL," +
            " NAME TEXT NOT NULL, " +
            " AGE INT NOT NULL, " +
            " ADDRESS CHAR(50), " +
            " SALARY REAL)";
         stmt.executeUpdate(sql);
         stmt.close();
         c.close();
      } catch ( Exception e ) {
         System.err.println( e.getClass().getName()+": "+ e.getMessage() );
         System.exit(0);
      }
      System.out.println("Table created successfully");
   }
}

Output

Connection established successfully
Table created successfully
raja
Published on 02-Apr-2019 16:44:19
Advertisements