一、导入spring+版本号的jar包,本文最下面提供下载
二、创建数据库
create database resources; create table resource( id varchar(20),name varchar(20),size long,uploader varchar(20) ,uploadtime varchar(20),path varchar(20),downloadcount int )
三、使用数据库连接池来获取连接(如果使用数据库连接池,可使用c3p0来获取连接在本博客可以找到,使用超级方便)
这里我就不多做介绍了
四、下面就使用JDBCtemplate来实现增删改查等常见操作
package com.itcast.dao; import java.util.LinkedList; import java.util.List; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import com.itcast.javabean.Resource; import com.itcast.utils.JdbcUtils; public class ResourceDao_template { public boolean add(Resource bean) { JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDatasource()); String sql = "insert into resource (id,name,size,uploadtime,uploader,downloadcount,path) values (" + "?,?,?,?,?,?,?)"; int resultInt = template.update(sql, new Object[] { bean.getId(), bean.getName(), bean.getSize(), bean.getUploadtime(), bean.getUploader(), bean.getDownloadcount(), bean.getPath() }); if (resultInt > 0) { return true; } return false; } public boolean delete(String id) { JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDatasource()); String sql = "delete from resource where id=?"; int resultInt = template.update(sql, new Object[] { id }); if (resultInt > 0) { return true; } return false; } public boolean update(Resource bean) { JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDatasource()); String sql = "update resource set name=?,size=?,uploadtime=?,uploader=?,downloadcount=?,path=? where id=?"; int resultInt = template.update(sql, new Object[] { bean.getName(), bean.getSize(), bean.getUploadtime(), bean.getUploader(), bean.getDownloadcount(), bean.getPath(), bean.getId() }); if (resultInt > 0) { return true; } return false; } public List<Resource> getAll() { JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDatasource()); String sql = "select id from resource"; List<String> ids = template.queryForList(sql, String.class); // template.query(sql, rowMapper) List<Resource> list = new LinkedList<Resource>(); for (String id : ids) { System.out.println(id); Resource resource = find(id); list.add(resource); resource = null; } return list; } public Resource find(String id) { JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDatasource()); String sql = "select * from resource where id=?"; Resource res = (Resource) template.queryForObject(sql, new Object[] { id }, new BeanPropertyRowMapper(Resource.class)); return res; } public int getTotalRecord() { JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDatasource()); String sql = "select count(*) from resource"; int totalRecord = template .queryForInt(sql, new Object[] { "count(*)" }); return totalRecord; } }