java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.spring.jdbc;

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

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

public class SpringJdbcInsertDemo {
    private static final String sql = "INSERT INTO students (first_name, last_name) VALUES (?, ?)";

    private DataSource dataSource;

    public SpringJdbcInsertDemo(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void saveStudent(String firstName, String lastName) {
        //
        // 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[] {firstName, lastName};
        int[] types = new int[] {Types.VARCHAR, Types.VARCHAR};

        //
        // Calls JdbcTemplate.update() methods to create a new record
        // in the students 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();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost/javacoderanch");
        dataSource.setUsername("root");
        dataSource.setPassword("");
        return dataSource;
    }

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

        SpringJdbcInsertDemo demo = new SpringJdbcInsertDemo(dataSource);
        demo.saveStudent("Paul", "Allen");
        demo.saveStudent("John", "Gecko");
    }
}