PostgreSQL is a free and open-source ORDBMS which is known for its extensibility and SQL compliance. It is recommended, for storing a high volume of data, thus used in major web development projects, which can produce a large amount of user-generated data.
Download GUI setup from the official website
After clicking on Download the Installer, you’ll get the list of different setups. From the list, Select Windows x86-64 for row 12.X
After completion of Download, open the Setup file, and you’ll get the following screen, click on the Next button.
5432
). Do not change if you are a beginner.Wait for the process to complete.
Setup Complete
Change the Path
variable for the system to make PostgreSQL globally available.
bin
folder of the Postgres installation directory.To test the Postgres Installation:
psql -U postgres
postgres=#
\du
to list all the available users\l
to list all the databases\conninfo
to view connection infopsql
not found: That means the environment variable is not correctly setup.In the above setup, you will also get GUI Software for Database Management called PGAdmin4
. You can find the executable in the directory pgadmin/pgadmin4.exe
inside the Installation Folder. In the left pane, you can select the server. When selected, it will ask the password for postgres user, you should enter the same password that you set during installation.
The GUI will open in the browser and will look like this.
First update system repositories
sudo apt-get update
Install PostgreSQL
sudo apt-get install postgresql
We can also add Contrib packages for additional functionalities
sudo apt-get install postgresql postgresql-contrib
Open PostgreSQL
sudo -u postgres psql
To exit PostgreSQL CUI, use \q
and hit Enter
.
postgres=# \q
To create a user
sudo -u postgres createuser --i
Enter the name of role to add: my_user
Shall the new role be a superuser? (y/n) y
To create a database
sudo -u postgres createdb my_db
To connect via the created role
sudo -u my_user psql
To check Connection Info, after the above command
/conninfo
Output:
You are now connected to database "my_db" as user "my_user" via socket in "<Postgres Installation path>" at port "5432"
To locate config files, use ls etc/postgresql/<version>/main/
ls etc/postgresql/12/main/
conf.d pg_ctl.conf pg_ident.conf start.conf environment pg_hba.conf postgresql.conf
To use GUI for PostgreSQL, you can download PGAdmin3
from the Ubuntu Software
.
Java Database Connectivity (JDBC) is the standard API that enables Java applications to connect with the various databases.
For the following content, you are expected to have a basic knowledge of Java and DBMS.
To use JDBC, you should have a database with a user which have sufficient privileges on that database. JDBC also needs that user’s name and password to create a connection with the database.
postgres=# CREATE DATABASE my_database;
CREATE DATABASE
postgres=# CREATE USER temp_user WITH ENCRYPTED PASSWORD 'temp_password';
CREATE ROLE
postgres=# GRANT ALL PRIVILEGES ON DATABASE my_database to temp_user;
GRANT
postgres=#
Apart from this, users must also have the PostgreSQL Drivers for JDBC. These drivers can be downloaded from the postgresql website.
Netbeans is the official Java IDE and managed by Oracle.
Projects
and select Properties
.Add Library
and search for the PostgreSQL driver and select it.Add JAR/Folder
and select downloaded Drivers.File
and then select Project Structure
.Library
in Project Settings
Menu in Left Pane.+
Plus button in Main Pane.Prerequisites: A Database and UserName and Password for the user with privileges on the Database.
package com.personal;
import java.sql.Connection;
import java.sql.DriverManager;
public class Main {
public static void main(String[] args) {
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/my_database", // Connection String
"temp_user", // Database User Name
"temp_password"); // Database User Password
System.out.println("Opened database successfully");
if (conn.getMetaData().supportsBatchUpdates()) {
System.out.println("The Database drivers support Batch Updates");
} else {
System.out.println("The Database drivers does not support Batch Updates");
}
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
}
Output:
Opened database successfully
The Database drivers support Batch Updates
In the above program:
Class.forName
initializes the PostgreSQL Drivers."<DriverClass>://<Database_Host>:<Database_Port>/<Database_Name>"
Password authentication failed for user "<user>"
Possible Cause: If user name or password is incorrect.
database "my_database" does not exist
Possible Cause: If the database my_database
is not present.
package com.personal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void createTable(Connection conn) throws SQLException {
final Statement statement = conn.createStatement();
String query = "CREATE TABLE post " +
"(id SERIAL NOT NULL, " +
"content VARCHAR(255), " +
"likes INTEGER, " +
"PRIMARY KEY (id))";
statement.executeUpdate(query);
}
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/my_database","temp_user", "temp_password");
System.out.println("Creating Table `Post`");
createTable(conn);
System.out.println("Created Table `Post`");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Output:
Creating Table `Post`
Created Table `Post`
createTable()
method creates a table with columns id
, content
, and likes
where id
is Auto-Generated, Primary key for the table; content
is a string which contains the content of the posts; likes
is an integer that will store the total likes given to the post.Statement
object to create a static statement for a database.executeUpdate()
to execute the statement. Here, executeStatement()
will return 0
(zero) by default.SQLException
if any database access occurs.Relation "post" already exists
: If post
table is already present in the Database.To verify that the table is created, you can do any of the following:
PSQLException
is thrown with the message “Table already exists”.Open psql
in the terminal with the following command: psql -U temp_user -d my_database
and then enter the respective password. After this, enter command \dt;
, and you will get the following output
my_database=> \dt;
List of relations
Schema | Name | Type | Owner
--------+------+-------+-----------
public | post | table | temp_user
(1 row)
package com.personal;
import java.sql.*;
public class Main {
public static void addPost(Connection conn, String content, int likes) throws SQLException {
String query = "INSERT INTO post(content, likes) VALUES (?, ?)";
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, content);
statement.setInt(2, likes);
statement.executeUpdate();
}
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/my_database", "temp_user", "temp_password");
System.out.println("Creating `Post`");
addPost(conn, "This is my First post by JDBC", 1);
System.out.println("Successfully Created First `Post`");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Output:
Creating `Post`
Successfully Created `Post`
addPost()
takes Connection
as the parameter with the content
and likes
for a Post. And then add the create a new record with passed content
and likes
in the post table.PreparedStatement
instead of Statement
because the Query is dynamic.PreparedStatement
is used when the queries are dynamic or queries are reused.executeUpdate()
method to execute statement. Here, the method should return 1
(One) which represents the addition of one record. User can check the value by enclosing the executeUpdate()
line inside the System.out.println()
.To verify that the record is added in the table, you should follow these steps:
psql -U temp_user -d my_database
and then enter the respective password.Then the records can be viewed by the following command SELECT * from post
, and you will get the following output.
my_database=> SELECT * from post;
id | content | likes
----+-------------------------------+-------
1 | This is my First post by JDBC | 1
(1 row)
package com.personal;
import java.sql.*;
public class Main {
public static void printAllPosts(Connection conn) throws SQLException {
final Statement statement = conn.createStatement();
final String query = "SELECT * FROM post";
ResultSet result = statement.executeQuery(query);
while (result.next()) {
int id = result.getInt("id");
String content = result.getString("content");
int likes = result.getInt("likes");
System.out.printf("Post with Id = %d had content = '%s' with %d likes\n", id, content, likes);
}
}
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/my_database","temp_user", "temp_password");
System.out.println("Content of table `Post`:");
printAllPosts(conn);
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Output:
Content of table `Post`:
Post with Id = 1 had content = 'This is my First post by JDBC' with 1 likes
printAllPosts()
prints all the posts of the table post
.Statement
object to form a query because the required query is static.executeQuery()
method to execute the Statement and unlike executeUpdate()
method, this method returns a ResultSet
which has all the records that are produced by the query.ResultSet
will have a cursor on the first record of the queried data. The Queried record can be fetched by the next()
method of ResultSet
which moves the cursor to the next record.getInt()
and getString()
methods are used to get the Data of a result where the parameter will specify the column for which method is called, and the return value will be the value of the specified column.package com.personal;
import java.sql.*;
public class Main {
public static void updateLikes(Connection conn, Integer id, Integer likes) throws SQLException {
String query = "UPDATE post set likes = ? WHERE id = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, likes);
statement.setInt(2, id);
statement.executeUpdate();
}
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/my_database", "temp_user", "temp_password");
System.out.println("Updating Likes for Post with id 1 to 5 likes");
updateLikes(conn, 1, 5);
System.out.println("Update Successful");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Output:
Updating Likes for Post with id 1 to 5 likes
Update Successful
updateLikes()
will take the Connection
with the id
of the desired post and new Count of likes
for that post as parameters. It is used to update the likes
for the post with id
passed as parameters.PreparedStatement
is used, since the parameters id
and likes
will get updated with each call.executeUpdate()
will execute the Statement and returns the count of the records affected by the query. In this case, the count should be 1
(One).You can verify the above program by the following methods:
printAllPosts()
method and find the post with id
= 1 from the output and check whether its likes
got updated to 1 or not.Can run the following query directly in psql: SELECT * FROM post WHERE id = 1
, and you will get the following output.
my_database=> SELECT * FROM post WHERE id = 1;
id | content | likes
----+-------------------------------+-------
1 | This is my First post by JDBC | 5
(1 row)
package com.personal;
import java.sql.*;
public class Main {
public static void deletePost(Connection conn, Integer id) throws SQLException {
String query = "DELETE FROM \"post\" WHERE id = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, id);
statement.executeUpdate();
}
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/my_database", "temp_user", "temp_password");
System.out.println("Deleting Post with id 1 from table `Post`:");
deletePost(conn, 1);
System.out.println("Deletion Successful");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Output:
Deleting Post with id 1 from table `Post`:
Deletion Successful
deletePost()
method takes Connection
as a parameter with the id
of the post for deletion.PreparedStatement
to form a statement and uses executeUpdate()
to execute the statement.
Here, executeUpadate()
will return the count of records affected by the execution of the statement and should be equal to 1
(One).User can verify the above program using the following methods
printAllPost()
method to print the Posts, and try to find the Post with Id = 1, if not found then the program worked correctly.Can run the following Query, directly in psql: SELECT * FROM post WHERE id = 1
, and you will get the following output.
my_database=> SELECT * FROM post WHERE id = 1;
id | content | likes
----+---------+-------
(0 rows)
executeUpdate() | executeQuery() |
---|---|
executeUpdate() is generally used to execute the statement which doesn’t return any column (DML Queries like UPDATE query) | executeQuery() is used when the execution of statements will return one or more records. (SELECT statements) |
executeUpdate() returns an integer which represents the number of records affected by the executed DML query or in case of other queries it returns 0. | executeQuery() returns the ResultSet which has the records produced by the query and will have the cursor pointing to the first record. |
Statement | PreparedStatement |
---|---|
The Statement is static, and hence will result in the same query in each execution | PreparedStatement is dynamic and can be modified by the parameters which can be set dynamically. |
The Statement is generally used for one time. The Statement queries will result in the same query every but the output may vary based on the other queries ran in the middle of the two uses of Statement. | PreparedStatement can be reused any number of times. Whenever parameters are changed, the query will change. This is faster than creating a new Statement every time. |
SQL: Structured Query Language is used to access and manage RDBMS. It is famous for its simplicity, usefulness, and similarity with the English language. It provides functionality to
Help us improve this content by editing this page on GitHub