日期:2014-05-16 浏览次数:20446 次
Spring中使用JDBC做的增删改查
? ? 有三种方式使用JDBC。
1、使用JdbcTemplate类,实现使用JDBC ,参数是用object数组传递的
?业务类:
public class UserDaoImpl implements UserDao{ // 定义一个Jdbc private JdbcTemplate jt; // 必须有set 方法,因为是通过set方法装配的 public void setJt(JdbcTemplate jt) { this.jt = jt; } @Override public void delete(int id) { // TODO Auto-generated method stub String sql="delete from user where id="+id; int temp=this.jt.update(sql); if(temp>0){ System.out.println("删除成功!"); }else{ System.out.println("删除失败!"); } } @Override public void insert(User entity) { // TODO Auto-generated method stub String sql="insert into user(name,age,sex) values(?,?,?)"; Object obj[]={entity.getName(),entity.getAge(),entity.getSex()}; int temp=this.jt.update(sql,obj); if(temp>0){ System.out.println("插入成功!"); }else{ System.out.println("插入失败!"); } } @Override public List<User> selectAll() { String sql="select * from user"; List list=this.jt.query(sql,new RowMapper(){ @Override public Object mapRow(ResultSet rs, int row) throws SQLException { // TODO Auto-generated method stub User user=new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setAge(rs.getInt("age")); user.setSex(rs.getString("sex")); return user; } }); System.out.println(list.size()); // TODO Auto-generated method stub return list; } @Override public User selectById(int id) { // TODO Auto-generated method stub String sql="select id,name,age,sex from user where id="+id; User user=(User)jt.queryForObject(sql, new RowMapper(){ @Override public Object mapRow(ResultSet rs, int arg1) throws SQLException { // TODO Auto-generated method stub User user=new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setAge(rs.getInt("age")); user.setSex(rs.getString("sex")); return user; } }); return user; } @Override public void update(User entity) { // TODO Auto-generated method stub String sql="update user set name=?,age=?,sex=? where id=?"; Object obj[]={entity.getName(),entity.getAge(),entity.getSex(),entity.getId()}; int temp=jt.update(sql,obj); if(temp>0){ System.out.println("更新成功!"); }else{ System.out.println("更新失败!"); } } }??
Xml中的部分代码:
<!-- 分散配置 --> <context:property-placeholder location="jdbc.properties" /> <!-- c3p0的数据源,设置它是为了配置jbdcTemplate--> <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 驱动程序 --> <property name="driverClass"> <value>${driverClass}</value> </property> <!-- 用户名 --> <property name="user"> <value>${username}</value> </property> <!-- 密码 --> <property name="password"> <value>${password}</value> </property> <!-- url --> <property name="jdbcUrl"> <value>${url}</value> </property> <!-- 最大池数 --> <property name="maxPoolSize"> <value>${c3p0.pool.max}</value> </property> &l