以下示例显示了如何使用Spring的JdbcTemplate类将记录插入数据库。
package org.nhooo.example.spring.jdbc; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; import java.sql.Types; import java.util.Date; public class InsertDemo { private static final String sql = "INSERT INTO records (title, " + " release_date, " + " artist_id, " + " label_id, " + " created) " + "VALUES (?, ?, ?, ?, ?)"; private DataSource dataSource; public InsertDemo(DataSource dataSource) { this.dataSource = dataSource; } public void saveRecord(String title, Date releaseDate, Integer artistId, Integer labelId) { // 创建JdbcTemplate的实例并传递连接 // 到数据库。 JdbcTemplate template = new JdbcTemplate(this.dataSource); // 定义查询参数和相应的SQL类型 Object[] params = new Object[] { title, releaseDate, artistId, labelId, new Date() }; int[] types = new int[] { Types.VARCHAR, Types.DATE, Types.INTEGER, Types.INTEGER, Types.DATE }; // 调用JdbcTemplate.update()方法创建一个新数据 //在记录表中。通常,更新方法将 // 返回执行的查询处理的行数 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/mediadb"); dataSource.setUsername("root"); dataSource.setPassword(""); return dataSource; } public static void main(String[] args) { DataSource dataSource = getDataSource(); InsertDemo demo = new InsertDemo(dataSource); demo.saveRecord("Rock Beatles", new Date(), 1, 1); } }