package org.spring.source.jdbc.template;
import java.sql.SQLException; import java.util.List;
import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.sql.ResultSet;
public class JdbcRantDao extends JdbcDaoSupport{ //写入Motorist的SQL语句 private static final String MOTORIST_INSERT = "insert into motorist(id,email,password,firstName,lastName)values(null,?,?,?,?)"; //获取所有Motorist的SQL语句 private static final String MOTORIST_SELECT = "select id,email,password,firstName,lastName from motorist"; //获取某一个Motorist的SQL语句 private static final String MOTORIST_BY_ID_SELECT = MOTORIST_SELECT + " where id=?"; /** * 利用JDBC模板往数据库里添加一行数据 * @param motorist */ public void saveMotorist(Motorist motorist){ getJdbcTemplate().update(MOTORIST_INSERT, new Object[] {motorist.getEmail(),motorist.getPassword(),motorist.getFirstName(),motorist.getLastName()}); } /** * 利用JDBC模板从数据库中读取一个数据 * @param id * @return */ public Motorist getMotoristById(int id){ List matches = getJdbcTemplate().query(MOTORIST_BY_ID_SELECT, new Object[] {Integer.valueOf(id)}, new RowMapper(){ public Object mapRow(ResultSet rs,int rowNum) throws SQLException,DataAccessException{ Motorist motorist = new Motorist(); motorist.setId(rs.getInt(1)); motorist.setEmail(rs.getString(2)); motorist.setPassword(rs.getString(3)); motorist.setFirstName(rs.getString(4)); motorist.setLastName(rs.getString(5)); return motorist; } }); return matches.size() > 0 ? (Motorist) matches.get(0) : null; } } |