The code below demonstrates on how to delete some records from database using the JdbcTemplate
.
package org.kodejava.spring.jdbc;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
public class DeleteDemo {
public static final String DRIVER = "com.mysql.cj.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost/musicdb";
public static final String USERNAME = "root";
public static final String PASSWORD = "";
public static final String QUERY = "DELETE FROM record WHERE id = ?";
private final DataSource dataSource;
public DeleteDemo(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Returns a DataSource object.
*
* @return a DataSource.
*/
public static DataSource getDataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(DeleteDemo.DRIVER);
ds.setUrl(DeleteDemo.URL);
ds.setUsername(DeleteDemo.USERNAME);
ds.setPassword(DeleteDemo.PASSWORD);
return ds;
}
public static void main(String[] args) {
DataSource ds = getDataSource();
DeleteDemo demo = new DeleteDemo(ds);
Long id = 1L;
demo.deleteRecord(id);
}
public void deleteRecord(Long id) {
// Creates an instance of JdbcTemplate and supply a data
// source object.
JdbcTemplate template = new JdbcTemplate(this.dataSource);
// Delete a record from database where the record
// id matches with the specified parameter.
Object[] params = {id};
int rows = template.update(DeleteDemo.QUERY, params);
System.out.println(rows + " row(s) deleted.");
}
}
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.1.10</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024