JDBC封装BaseDao
public class BaseDao { /**连接*/ protected Connection con ; /**SQL语句执行对象*/ protected PreparedStatement ps ; /**结果集*/ protected ResultSet rs ; static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public void setConnection() { try { con = DriverManager.getConnection( "jdbc:mysql://localhost:6788/test?characterEncoding=utf-8", "root","xxxx"); } catch (SQLException e) { e.printStackTrace(); } } public void closeConnection() { try { if(rs != null) { rs.close(); } if(ps != null) { } if(con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } }
/** * 更新数据 * @param sql 语句 * @param valueArray 占位符列表 */ public void updateDate(String sql,Object...valueArray) { this.setConnection(); try { ps = con.prepareStatement(sql); for (int i = 0; i < valueArray.length; i++) { ps.setObject(i+1, valueArray[i]); } ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { this.closeConnection(); } }
方法一:
public List find(String sql,Class c,Object...valueArray){ List list = new ArrayList(); this.setConnection(); try { ps = con.prepareStatement(sql); if(valueArray != null) { for (int i = 0; i < valueArray.length; i++) { ps.setObject(i+1, valueArray[i]); } } rs=ps.executeQuery(); //得到结果集的审查对象 ResultSetMetaData rm = rs.getMetaData(); //得到查询结果的列数 int num = rm.getColumnCount(); while(rs.next()) { Object obj = c.newInstance(); for (int i = 1; i <= num; i++) { //得到对应列的列名 String columnName = rm.getColumnName(i); Object columnObj = rs.getObject(columnName); //根据列名,得到属性对象 Field f = c.getDeclaredField(columnName); f.setAccessible(true); //将对象指定的属性赋值为columnObj f.set(obj, columnObj); } list.add(obj); } } catch (Exception e) { e.printStackTrace(); }finally { this.closeConnection(); } return list; }
方法二:
public List find(String sql,Class c,Object...valueArray){ List list = new ArrayList(); this.setConnection(); try { ps = con.prepareStatement(sql); if(valueArray != null) { for (int i = 0; i < valueArray.length; i++) { ps.setObject(i+1, valueArray[i]); } } //实体类属性列表 Field[] f = c.getDeclaredFields(); rs=ps.executeQuery(); while(rs.next()) { Object obj = c.newInstance(); for (int i = 0; i < f.length; i++) { //去掉访问修饰符的检查 f[i].setAccessible(true); String fname = f[i].getName(); try { Object columnObj = rs.getObject(fname); f[i].set(obj, columnObj); } catch (Exception e) { continue; } } list.add(obj); } } catch (Exception e) { e.printStackTrace(); }finally { this.closeConnection(); } return list; }