- JDBC Create a Table Example
- JDBC Insert Multiple Rows Example
- JDBC Update Query Example
- JDBC Select Query Example
- JDBC Delete Query Example
- JDBC Transaction Management Example
- JDBC Connection to Oracle Database Example
- JDBC Connection to PostgreSQL Example
- JDBC Connection to H2 Database Example
- Java JDBC Connection to HSQLDB Database
- Java PostgreSQL Example
- Java H2 Create Table Example
- Java H2 Insert Record Example
- Java H2 Embedded Database 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
Create Table Script
Insert Record in PostgreSQL database
Make sure that you have installed PostgreSQL database in your machine.
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 IF NOT EXISTS authors (
id serial PRIMARY KEY,
name VARCHAR(25)
);
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JavaPostgreSqlPrepared {
public static void main(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
Post a Comment