15 posts
This article tells you how to connect the postgresql with java program. If we connect to the postgresql we can perform operations directly from the java program without doing the operations in postgresql.
To connect to the Postgresql database server from a java , you need to have a Postgresql driver.
So download the driver with this link : https://jdbc.postgresql.org/download.html
The downloaded file is a jar file. You should copy it to a specific java program which you want to connect to the Postgresql server.
You create a New Java Project and add that driver with the following manner to your project
Right click on the created project --> Properties --> Java Build Path --> Libraries --> Add External JARs --> Add the driver which you downloaded.
The address of the PostgreSQL database server e.g., localhost.
The database name e.g., employee.
(You can get the database name in postgresql with the command: select current_database())
The username and password of the account that you will use to connect to the database.
private final String url = "jdbc:postgresql://localhost/employee";
private final String username = "postgres";
private final String password = "<add your password>";
conn = DriverManager.getConnection(url, user, password);
Package Postgres;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Hello{
private final String url = "jdbc:postgresql://localhost/dvdrental";
private final String user = "postgres";
private final String password = "<add your password>";
//Connecting to the Postgres
public Connection connect() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the PostgreSQL server successfully.");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
public static void main(String[] args) {
Hello post = new Hello();
post.connect();
}
}
When you run it, your program is connected to the postgresql.
Please log in to leave a comment.