Java PostgreSQL Example

In this post, we will learn how to insert a record into a PostgreSQL database using the JDBC API.

Make sure that you have installed PostgreSQL database in your machine.

PostgreSQL driver

To include the PostgreSQL Java driver, we need to add the following Maven dependency:
<dependency>    <groupId>org.postgresql</groupId>    <artifactId>postgresql</artifactId>    <version>42.2.0</version></dependency>

Create Table Script

CREATETABLEIF NOT EXISTS authors (    idserialPRIMARY KEY,     nameVARCHAR(25));

Insert Record in PostgreSQL database

importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.SQLException;importjava.util.logging.Level;importjava.util.logging.Logger;publicclassJavaPostgreSqlPrepared {publicstaticvoidmain(String[]args) {String url="jdbc:postgresql://localhost:5432/testdb";String user="user name here";String password="password here";int id=6;String author="Trygve Gulbranssen";String query="INSERT INTO authors(id, name) VALUES(?, ?)";try (Connection con=DriverManager.getConnection(url, user, password);PreparedStatement pst= con.prepareStatement(query)) {            pst.setInt(1, id);            pst.setString(2, author);            pst.executeUpdate();        }catch (SQLException ex) {Logger lgr=Logger.getLogger(JavaPostgreSqlPrepared.class.getName());            lgr.log(Level.SEVERE, ex.getMessage(), ex);        }    }}


Comments