English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Interfaccia JAVA PostgreSQL

Installazione

Inizia a utilizzare PostgreSQL nel nostro programma Java Prima di tutto, dobbiamo assicurarci che PostgreSQL JDBC e Java siano installati sul nostro computer. Puoi controllare Java Tutorial, to learn how to install it on your machine Java. Now let's check how to set up the postgresqljdbc driver.

  • Download the latest version of postgresql-(version).jdbc.jar from the following address postgresql-jdbc Download.

  • Add the downloaded jar file postgresql-(VERSION).jar, or you can use it with the -classpath option as shown in the following example.

The following part assumes that you are familiar with the javajdbc concept. If not, it is recommended that you spend half an hour learning the JDBC tutorial to familiarize yourself with the concepts explained below.

Connect to the database

The following Java code shows how to connect to an existing database. If the database does not exist, it will be created, and finally, a database object will be returned.

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");
         c = DriverManager
            .getConnection("jdbc:postgresql://localhost:5432/testdb",
            "postgres", "123");
      catch (Exception e) {
         e.printStackTrace();
         System.err.println(e.getClass().getName()+": " +e.getMessage());
         System.exit(0);
      }
      System.out.println("Opened database successfully");
   }
}

Before compiling and running the above program, please find the pg_hba.conf file in the PostgreSQL installation directory, create a file, and add the following lines:

# IPv4 local connections:
host all all all 127.0.0.1/32 md5

If the postgres server is not running, you can use the following command to start/restart the postgres server:

Now, let's compile and run the above program to connect to testdb. Here, we use postgres as the user ID 123 is used as the password to access the database. You can change it according to the database configuration and settings. We also assume that the current version of the JDBC driver postgresql-9.2-1002.jdbc3.jar is available in the current path.

C:\JavaPostgresIntegration>javac PostgreSQLJDBC.java
C:\JavaPostgresIntegration>java -cp c:\tools\postgresql-9.2-1002.jdbc3.jar;C:\JavaPostgresIntegration PostgresqlJDBC
Database opened successfully

Create table

The following Java program will be used to create a table in the previously opened database. Make sure that there is no such table in the target database.

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("Opened database 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");
   }
}

While compiling and executing the program, it will create the COMPANY table in the testdb database and display the following two lines-

Database aperta con successo
Table created successfully

INSERT operation

The following Java program demonstrates how to create records in the COMPANY table created in the above example-

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");
         c.setAutoCommit(false);
         System.out.println("Opened database successfully");
         stmt = c.createStatement();
         String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
            + "VALUES (1, 'Paul', 32, 'California', 20000.00 );"
         stmt.executeUpdate(sql);
         sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
            + "VALUES (2, 'Allen', 25, 'Texas', 15000.00 );"
         stmt.executeUpdate(sql);
         sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
            + "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );"
         stmt.executeUpdate(sql);
         sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
            + "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"
         stmt.executeUpdate(sql);
         stmt.close();
         c.commit();
         c.close();
      catch (Exception e) {
         System.err.println(e.getClass().getName() + ": " + e.getMessage());
         System.exit(0);
      }
      System.out.println("Records created successfully");
   }
}

While compiling and executing the above program, it will create the given record in the COMPANY table and display the following two lines-

Database aperta con successo
Records created successfully

Operazione SELECT

Il seguente programma Java mostra come ottenere e visualizzare i record dalla tabella COMPANY creata negli esempi precedenti

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
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");
         c.setAutoCommit(false);
         System.out.println("Opened database successfully");
         stmt = c.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * FROM COMPANY;");
         while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");
            String address = rs.getString("address");
            float salary = rs.getFloat("salary");
            System.out.println("ID = " + id);
            System.out.println("NAME = " + name);
            System.out.println("AGE = " + age);
            System.out.println("ADDRESS = " + address);
            System.out.println("SALARY = " + salary);
            System.out.println();
         }
         rs.close();
         stmt.close();
         c.close();
      } catch (Exception e) {
         System.err.println(e.getClass().getName() + ": " + e.getMessage());
         System.exit(0);
      }
      System.out.println("Operazione eseguita con successo");
   }
}

Quando il programma viene compilato ed eseguito, si ottiene il seguente risultato

Database aperta con successo
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0
ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
Operazione eseguita con successo

Operazione UPDATE

Esempio di codice Java che mostra come utilizzare l'istruzione UPDATE per aggiornare qualsiasi record e quindi ottenere e visualizzare i record aggiornati dalla nostra tabella COMPANY

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
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");
         c.setAutoCommit(false);
         System.out.println("Opened database successfully");
         stmt = c.createStatement();
         String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
         stmt.executeUpdate(sql);
         c.commit();
         ResultSet rs = stmt.executeQuery("SELECT * FROM COMPANY;");
         while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");
            String address = rs.getString("address");
            float salary = rs.getFloat("salary");
            System.out.println("ID = " + id);
            System.out.println("NAME = " + name);
            System.out.println("AGE = " + age);
            System.out.println("ADDRESS = " + address);
            System.out.println("SALARY = " + salary);
            System.out.println();
         }
         rs.close();
         stmt.close();
         c.close();
      } catch (Exception e) {
         System.err.println(e.getClass().getName() + ": " + e.getMessage());
         System.exit(0);
      }
      System.out.println("Operazione eseguita con successo");
   }
}

Quando il programma viene compilato ed eseguito, si ottiene il seguente risultato

Database aperta con successo
ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0
Operazione eseguita con successo

Operazione DELETE

Esempio di codice Java che mostra come utilizzare l'istruzione DELETE per eliminare qualsiasi record e quindi ottenere e visualizzare i record rimanenti dalla nostra tabella COMPANY

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class PostgreSQLJDBC6 {
   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");
         c.setAutoCommit(false);
         System.out.println("Opened database successfully");
         stmt = c.createStatement();
         String sql = "DELETE from COMPANY where ID = 2;";
         stmt.executeUpdate(sql);
         c.commit();
         ResultSet rs = stmt.executeQuery("SELECT * FROM COMPANY;");
         while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");
            String address = rs.getString("address");
            float salary = rs.getFloat("salary");
            System.out.println("ID = " + id);
            System.out.println("NAME = " + name);
            System.out.println("AGE = " + age);
            System.out.println("ADDRESS = " + address);
            System.out.println("SALARY = " + salary);
            System.out.println();
         }
         rs.close();
         stmt.close();
         c.close();
      } catch (Exception e) {
         System.err.println(e.getClass().getName() + ": " + e.getMessage());
         System.exit(0);
      }
      System.out.println("Operazione eseguita con successo");
   }
}

Quando il programma viene compilato ed eseguito, si ottiene il seguente risultato

Database aperta con successo
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0
Operazione eseguita con successo