1. Download Drive jar
: https://jdbc.postgresql.org/download.html
2. Importing the JAR Package
Create a new Lib folder and drag the downloaded Jar driver package to the folder.
Add the jar driver package to the libraries
3. The program code is as follows: Helloworld.java
Packagetest;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement; Public classHelloWorld { Public Static voidMain (String []args) {Connection Connection=NULL; Statement Statement=NULL; Try{String URL= "Jdbc:postgresql://127.0.0.1:5432/postgis"; String User= "Postgres"; String Password= "123456"; Class.forName ("Org.postgresql.Driver"); Connection=drivermanager.getconnection (URL, user, password); System.out.println ("Successfully connected to PG database" +connection); String SQL= "SELECT name from Test"; Statement=connection.createstatement (); ResultSet ResultSet=statement.executequery (SQL); while(Resultset.next ()) {String name=resultset.getstring (1); SYSTEM.OUT.PRINTLN (name); } }Catch(Exception e) {Throw NewRuntimeException (e); }finally{ Try{statement.close (); } Catch(SQLException e) {e.printstacktrace (); Throw NewRuntimeException (e); }finally{ Try{connection.close (); } Catch(SQLException e) {e.printstacktrace (); Throw NewRuntimeException (e); } } } }}
Operation Result:
Java Connection PostgreSQL Database