JDBC dao层增删改查实现
1.在实现增删改查时,首先应先声明一个成员变量,QueryRunner类型的成员变量,注意不要使用无参构造方法,要将连接池的对象传入其中。
private QueryRunner queryRunner = new QueryRunner(DButil.getDruidDataSource());
在QueryRunner类中有增删改的方法,QueryRunner.update()想方法中传入sql语句即可
//插入代码
private QueryRunner queryRunner = new QueryRunner(DButil.getDruidDataSource()); //插入 public boolean insert(person person) { boolean result = false; Object[] prams = {person.getHousetype(),person.getHometype(),person.getHomearea(),person.getHomenummber(),person.getMaster(),person.getIdnummber(),person.getSex(),person.getNation(),person.getEducation()}; try { int result1 = queryRunner.update("insert into person(housetype,hometype,homearea,homenummber,master,idnummber,sex,nation,education) value (?,?,?,?,?,?,?,?,?)",prams); if(result1 == 1) { result = true; } } catch (SQLException e) { e.printStackTrace(); } return result; }
//删除代码
public boolean delete(person person) { String name = person.getMaster(); boolean result = false; try { int resultq = queryRunner.update("delete from person where master=?",name); if (resultq == 1) result = true; } catch (SQLException e) { e.printStackTrace(); } return result; }
//修改代码
public boolean update(person person) { // String name = person.getMaster(); Object[] params = {person.getIdnummber(),person.getSex(),person.getNation(),person.getEducation(),person.getMaster()}; try { int result = queryRunner.update("update person set idnummber=?,sex=?,nation=?,education=? where master=?",params); if(result == 1) return true; } catch (SQLException e) { e.printStackTrace(); } return false; }
//查找代码
查找单个所用到的方法为QueryRunner.query()
此方法的构造方法需要传入三个值,首先是sql语句,其次调用的是BeanHeadler方法其中泛型则是需要帮你转化为什么类型,这里视具体情况而定,BeanHeadler的构造方法中填的是你泛型的.class方法,
第三个传params数组
查找单个用到的是BeanHeadler
public person select(person person) { String name = person.getMaster(); try { person person1 = queryRunner.query("select * from person where master=?",new BeanHandler<person>(person.class),name); return person1; } catch (SQLException e) { e.printStackTrace(); } return null; }
查询所有用的是BeanListHeadler
public List<person> selectAll() { try { List<person> personList = queryRunner.query("select * from person",new BeanListHandler<person>(person.class)); return personList; } catch (SQLException e) { e.printStackTrace(); } return null; }