package dbutils;import org.junit.Test;import java.sql.ResultSet;import java.sql.SQLException;/**
* 仿commons-dbutils
* Created by kevin on 2020/4/2.
*/publicclassDemo2{@Testpublicvoidfun1(){// Stu stu = new Stu();// stu.setNumber("0002");// stu.setName("王五");// stu.setAge(30);// stu.setGender("男");// stu.setPassword("111111");// add(stu);
Stu stu2 =load("0002");
System.out.println(stu2.toString());}publicintadd(Stu stu){
QR<Stu> stuQr =newQR<Stu>(JdbcUtils.getDataSource());
String sql="insert into stu values(?,?,?,?,?)";
Object[] params ={stu.getNumber(),stu.getName(),stu.getAge(),stu.getGender(),stu.getPassword()};return stuQr.update(sql,params);}public Stu load(String number){
QR<Stu> stuQr =newQR<Stu>(JdbcUtils.getDataSource());
String sql="select * from stu where number=?";
Object[] params ={number};
RsHandler<Stu> rh =newRsHandler<Stu>(){@Overridepublic Stu handle(ResultSet rs)throws SQLException{if(!rs.next())return null;
Stu stu =newStu();
stu.setNumber(rs.getString("number"));
stu.setName(rs.getString("name"));
stu.setAge(rs.getInt("age"));
stu.setGender(rs.getString("gender"));
stu.setPassword(rs.getString("password"));return stu;}};return stuQr.query(sql,rh,params);}}
使用commons-dbutils
package dbutils;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.ResultSetHandler;import org.apache.commons.dbutils.handlers.BeanHandler;import org.junit.Test;import java.sql.ResultSet;import java.sql.SQLException;/**
* commons dbutils
* Created by kevin on 2020/4/2.
*/publicclassDemo3{@Testpublicvoidfun1(){
QueryRunner qr=newQueryRunner(JdbcUtils.getDataSource());
String sql="insert into stu values(?,?,?,?,?)";
Object[] params ={"0003","李四",30,"男","111111"};try{
qr.update(sql,params);}catch(SQLException e){
e.printStackTrace();}}@Testpublicvoidfun2(){
QueryRunner qr=newQueryRunner(JdbcUtils.getDataSource());
String sql="select * from stu where number=?";
Object[] params ={"0003"};try{// ResultSetHandler<Stu> handler = new ResultSetHandler<Stu>() {// @Override// public Stu handle(ResultSet rs) throws SQLException {// if(!rs.next()) return null;// Stu stu = new Stu();// stu.setNumber(rs.getString("number"));// stu.setName(rs.getString("name"));// stu.setAge(rs.getInt("age"));// stu.setGender(rs.getString("gender"));// stu.setPassword(rs.getString("password"));// return stu;// }// };//該部分代碼commons-dbutils已經有5個實現類了可以直接調用//BeanHandler類是ResultSetHandler實現類,BeanHandler類使用需知(數據庫列名必須與實體類名稱相同)
BeanHandler<Stu> beanHandler =newBeanHandler<Stu>(Stu.class);
Stu stu = qr.query(sql,beanHandler,params);
System.out.println(stu.toString());}catch(SQLException e){thrownewRuntimeException(e);}}}