此处写上应用JdbcTemplate的dao操作数据库的一些代码(含基本的增删改查,注:重点是查询出多条语句的写法):
package org.sakaiproject.zhaorui.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import org.sakaiproject.zhaorui.dao.StudentDao;
import org.sakaiproject.zhaorui.model.Student;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
@Repository
public class StudentDaoImpl implements StudentDao {
@Resource(name="jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@SuppressWarnings("unchecked")
@Override
public List<Student> selectAll() {
String sql = "select * from Student";
return jdbcTemplate.query(sql,new StudentMapper());
}
@Override
public void insertStudent(Student student) {
try {
jdbcTemplate.execute("insert into student(username,userpassword,userother) values("+student.getUsername()+","+student.getUserpassword()+","+student.getUserother()+")");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean updateStudent(Student student) {
try {
jdbcTemplate.update("update student set username="+student.getUsername()+",userpassword="+student.getUserpassword()+",userother="+student.getUserother()+" where usernumber = "+student.getUsernumber());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public boolean deleteStudent(Integer usernumber) {
try {
jdbcTemplate.execute("delete from student where usernumber="+usernumber);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
class StudentMapper implements RowMapper {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Student stu = new Student();
stu.setUsername(rs.getString("username"));
stu.setUsernumber(rs.getInt("usernumber"));
stu.setUserother(rs.getString("userother"));
stu.setUserpassword(rs.getString("userpassword"));
return stu;
}
}
注:如果查询出来的是一条结果或者结果是基本类型,用下面代码即可,不用重写rowMapper的借口
package org.sakaiproject.zhaorui.dao.impl;
import org.sakaiproject.zhaorui.dao.TestDao;
import javax.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class TestDaoImpl implements TestDao {
@Resource(name="jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@Override
public int count() {
return jdbcTemplate.queryForObject("select count(1) from sakai_user", Integer.class);
}
}
具体的SpringJDBC的例子请参照:http://my.oschina.net/u/218421/blog/38598,里面写的已经很详细了