Example to Update Database in Spring JDBC
November 05, 2013
In this page, we will learn how to update database in spring JDBC. We can update database using JdbcTemplate.update(). The SQL query will have placeholder (?) to take input for update. In our example we have taken a simple example to present the demo for database update.
FarmarDao.java
package com.concretepage.dao; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class FarmarDao { private JdbcTemplate jdbcTemplate; @Autowired public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public void setAge(int age, int id){ String sql = "update farmar set age =? where id=?"; this.jdbcTemplate.update(sql,age,id); } }
SpringTest.java
package com.concretepage; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.concretepage.dao.FarmarDao; public class SpringTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); FarmarDao farmar = (FarmarDao)context.getBean("farmarDao"); farmar.setAge(30, 1); System.out.println("Done"); } }
Table Schema
CREATE TABLE 'farmar' ( 'id' INT(10) NULL DEFAULT NULL, 'name' VARCHAR(50) NULL DEFAULT NULL, 'age' INT NULL DEFAULT NULL ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB;
example-to-update-database-in-spring-jdbc.zip