java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to delete records from database using JdbcTemplate?

The code below demonstrates on how to delete some records from database using the JdbcTemplate.

package com.javacoderanch.example.spring.jdbc;

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

import javax.sql.DataSource;

public class SpringJdbcDeleteDemo {
    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 = "DELETE FROM students WHERE id = ?";

    private DataSource dataSource;

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

    public void deleteStudent(Long id) {
        //
        // Creates an instance of JdbcTemplate and supply a data
        // source object.
        //
        JdbcTemplate template = new JdbcTemplate(this.dataSource);

        //
        // Delete a student record from database where the students
        // id matches with the specified parameter.
        //
        Object[] params = { id };
        int rows = template.update(SpringJdbcDeleteDemo.QUERY, params);
        System.out.println(rows + " row(s) deleted.");
    }

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

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

        Long id = 2L;
        demo.deleteStudent(id);
    }
}