1. 步骤一:创建数据库的表结构 create database spring_day03; use spring_day03; create table t_account( id int primary key auto_increment, name varchar(20), money double );2. 引入开发的jar包 * 先引入IOC基本的6个jar包 * 再引入Spring-aop的jar包 * 最后引入JDBC模板需要的jar包 * MySQL数据库的驱动包 * Spring-jdbc.jar * Spring-tx.jar 3.编写配置文件applicationContext.xml
4.创建UserBean类用于将查询结果进行保存或显示:
package com.huida.bean;public class UserBean { private int id; private String name; private double money; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } @Override public String toString() { return "UserBean [id=" + id + ", name=" + name + ", money=" + money + "]"; } }
5.创建BeanMapper类用于记录查询结果:
package com.huida.jdbc;import java.sql.ResultSet;import java.sql.SQLException;import org.springframework.jdbc.core.RowMapper;import com.huida.bean.UserBean;public class BeanMapper implements RowMapper{ @Override public UserBean mapRow(ResultSet rs, int arg1) throws SQLException { UserBean user=new UserBean(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setMoney(rs.getDouble("money")); return user; } }
6. 增删改查操作:
package com.huida.jdbc;import java.util.List;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.huida.bean.UserBean;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo3 { @Resource(name="jdbcTemplate") private JdbcTemplate jdbcTemplate; @Test //插入操作 public void run1(){ jdbcTemplate.update("insert into user values(null,?,?)","小明",10000); } @Test //修改操作 public void run2(){ jdbcTemplate.update("update user set name=?,money=? where id=?","思雨",1000,2); } @Test //删除操作 public void run3(){ jdbcTemplate.update("delete from user where id=?",2); } @Test //查询一条记录 public void run4(){ UserBean user=(UserBean) jdbcTemplate.queryForObject("select * from user where id=?", new BeanMapper(),1); System.out.println(user); } @Test //查询所有记录 public void run5(){ Listlist=jdbcTemplate.query("select * from user",new BeanMapper()); for(UserBean userBean:list){ System.out.println(userBean); } } }