How do I insert a new record into a database using JdbcTemplate?

The following example show you how to use the Spring’s JdbcTemplate class to insert a record into database.

package org.kodejava.example.spring.jdbc;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.sql.Types;
import java.util.Date;

public class InsertDemo {
    private static final String sql =
            "INSERT INTO records (title, " +
            "    release_date, " +
            "    artist_id, " +
            "    label_id, " +
            "    created) " +
            "VALUES (?, ?, ?, ?, ?)";

    private DataSource dataSource;

    public InsertDemo(DataSource dataSource) {
        this.dataSource = dataSource;

    public void saveRecord(String title, Date releaseDate,
                           Integer artistId, Integer labelId) {
        // Creates an instance of JdbcTemplate and passes a connection
        // to the database.
        JdbcTemplate template = new JdbcTemplate(this.dataSource);

        // Defines the query arguments and the corresponding SQL types
        // of the arguments.
        Object[] params = new Object[] {
                title, releaseDate, artistId, labelId, new Date()
        int[] types = new int[] {

        // Calls JdbcTemplate.update() methods to create a new data
        // in the records table. The update method in general will
        // return number of row / rows processed by the executed query
        int row = template.update(sql, params, types);
        System.out.println(row + " row inserted.");

    public static DriverManagerDataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        return dataSource;

    public static void main(String[] args) {
        DataSource dataSource = getDataSource();

        InsertDemo demo = new InsertDemo(dataSource);
        demo.saveRecord("Rock Beatles", new Date(), 1, 1);

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.