package com.baiyun.dao; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Properties; public class BaseDao { private static String driver=""; private static String url=""; private static String id=""; private static String pwd=""; protected Connection cn=null; protected PreparedStatement pst=null; protected ResultSet rst=null; static{ Properties ps=new Properties(); try { ps.load(BaseDao.class.getResourceAsStream("/jdbc.properties")); driver=ps.getProperty("jdbc.driver"); url=ps.getProperty("jdbc.url"); id=ps.getProperty("jdbc.id"); pwd=ps.getProperty("jdbc.pwd"); } catch (IOException e) { e.printStackTrace(); } try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //关闭数据库 protected void close_db() throws SQLException{ if(this.rst!=null){ this.rst.close(); } if(this.pst!=null){ this.pst.close(); } if(this.cn!=null){ this.cn.close(); } } //打开数据库,传入sql语句和参数,返回执行对象 private PreparedStatement open_db(String sql,Object... param) throws SQLException{ this.cn=DriverManager.getConnection(url, id, pwd); this.pst=this.cn.prepareStatement(sql); for(int i=0;i<param.length;i++){ this.pst.setObject(i+1,param[i]); } return this.pst; } //增、删、改的执行结果 private int update(PreparedStatement pt) throws SQLException{ int count=0; count=pt.executeUpdate(); this.close_db(); return count; } //分页的数据总条数 private int count(PreparedStatement pt) throws SQLException{ int count=0; this.rst=pt.executeQuery(); while(this.rst.next()){ count=this.rst.getInt(1); } this.close_db(); return count; } //分页查询 private ResultSet query(PreparedStatement pt) throws SQLException{ ResultSet rt=this.rst=pt.executeQuery(); return rt; } protected int update(String sql,List param) throws SQLException{ return this.update(sql, param.toArray()); } protected int update(String sql,Object... param) throws SQLException{ return this.update(this.open_db(sql, param)); } protected int count(String sql,List param) throws SQLException{ return this.count(sql, param.toArray()); } protected int count(String sql,Object... param) throws SQLException{ return this.count(this.open_db(sql, param)); } protected ResultSet query(String sql,List param) throws SQLException{ return this.query(sql, param.toArray()); } protected ResultSet query(String sql,Object... param) throws SQLException{ return this.query(this.open_db(sql, param)); } }