java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to update records in the database using JdbcTemplate?

The example demonstrated below will show you how to use the JdbcTemplate.update() method for updating records in database. This method returns an integer value indicating number of records updated in the database when the query is executed.

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 SpringJdbcUpdateDemo {
    public static final String DRIVER   = "com.mysql.jdbc.Driver";
    public static final String URL      = "jdbc:mysql://localhost/javacoderanchdb";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "";

    public static final String QUERY =
            "UPDATE students " +
            "SET first_name = ?, last_name = ? " +
            "WHERE id = ?";

    private DataSource dataSource;

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

    public static void main(String[] args) {
        DataSource ds = getDataSource();
        SpringJdbcUpdateDemo demo = new SpringJdbcUpdateDemo(ds);

        Long id = 1L;
        String firstName = "Alice";
        String lastName = "Mallory";
        demo.updateStudent(id, firstName, lastName);
    }

    public void updateStudent(Long id, String firstName, String lastName) {
        //
        // Creates an instance of JdbcTemplate and set the DataSource.
        // We can use the template update() method to update records
        // in the database. Below we use an update() method that accepts
        // three parameters: the sql query, the parameter values and
        // the parameter data types.
        //
        JdbcTemplate template = new JdbcTemplate(this.dataSource);
        
        Object[] params = {firstName, lastName, id};
        int[] types = {Types.VARCHAR, Types.VARCHAR, Types.BIGINT};
        
        int rows = template.update(SpringJdbcUpdateDemo.QUERY, params, types);
        System.out.println(rows + " row(s) updated.");
    }

    /**
     * Returns a data source object.
     * @return a DataSource.
     */
    public static DataSource getDataSource() {
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(SpringJdbcUpdateDemo.DRIVER);
        ds.setUrl(SpringJdbcUpdateDemo.URL);
        ds.setUsername(SpringJdbcUpdateDemo.USERNAME);
        ds.setPassword(SpringJdbcUpdateDemo.PASSWORD);
        return ds;
    }
}