最近由于项目需求,开发都是偏报表种类多,而且考虑到项目移植性,感觉还是用jdbc访问比较稳妥,等到项目移植的时候只需要修改相应的sql,以下是最近刚封装的jdbc,主要是通过重构封装增删改查,向外提供包括查询分页,模糊查询的方式,只需要把需要的参数封装成hashmap即可,请大家给点意见,
package com.micon.base.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.ObjectUtils; import com.micon.base.bean.Page; import com.micon.base.bean.ParamMap; import com.micon.base.bean.QueryBean; public class JdbcUtils { private static JdbcUtils jdbcUtils = null; public static JdbcUtils getJdbcUtils() { if (jdbcUtils == null) { jdbcUtils = new JdbcUtils(); } return jdbcUtils; } public Connection getConnection() throws ClassNotFoundException, SQLException { Connection con = DataBase.getConnection(); return con; } public int insert(String tableName, Map paramMap) throws Exception { String sql = genInsertSql(tableName, paramMap); //delete tab where id = ?, name = ? List param = new ArrayList(); if (null != paramMap && !paramMap.isEmpty()) { Set set = paramMap.entrySet(); for (Iterator it = set.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String key = ObjectUtils.toString(entry.getKey()).trim() .toLowerCase(); if (null != key && !"".equals(key)) { param.add(entry.getValue()); } } } return updateData(sql, param); } public int update(String tableName, Map paramMap) { return update(tableName,"id",paramMap); } public int update(String tableName, String primaryKey, Map paramMap) { String sql = genUpdateSql(tableName, primaryKey, paramMap); List param = new ArrayList(); if (null != paramMap && !paramMap.isEmpty()) { Set set = paramMap.entrySet(); String primary = ""; for (Iterator it = set.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String key = ObjectUtils.toString(entry.getKey()).trim() .toLowerCase(); if (null != key && !"".equals(key)) { if (null != entry.getValue()) { if (key.equals(primaryKey)) { primary = ObjectUtils.toString(entry.getValue()) .trim(); } else { param.add(entry.getValue()); } } } } if (null != primary && !"".equals(primary)) { param.add(primary); try { return updateData(sql, param); } catch (Exception e) { e.printStackTrace(); } } } return 0; } public int delete(String tableName, String filter) throws Exception { StringBuffer sql = new StringBuffer(" delete from " + tableName + " "); if (filter != null && !filter.equals("")) { sql.append(" where " + filter); } return updateData(sql.toString(), null); } public int updateData(String sql) throws Exception { return updateData(sql,null); } public int updateData(String sql, List param) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = getConnection(); ps = conn.prepareStatement(sql); if (param != null && param.size() > 0){ for (int i = 0; i < param.size(); i++) { ps.setObject(i + 1, param.get(i)); } } System.out.println(com.micon.base.util.DateUtils.DATEFORMAT_yMd_hms.format(new Date()) +" the update sql = [ " + sql+" ]"); return ps.executeUpdate(); } catch (SQLException ex) { System.out.println("Cannot execute sql: " + sql + "\nvalues:" + param + " error: " + ex.getMessage()); throw new Exception("Cannot execute sql: " + sql + "\nvalues:" + param + " error: " + ex.getMessage()); } finally { clean(ps, conn); } } private String genUpdateSql(String tableName, String primaryKey, Map mapValue) { String setSql = " set "; String whereSql = " where 1=1 "; if (null != mapValue && !mapValue.isEmpty()) { Set set = mapValue.entrySet(); for (Iterator it = set.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String key = ObjectUtils.toString(entry.getKey()).trim() .toLowerCase(); if (null != key && !"".equals(key)) { if (null != entry.getValue()) { if (key.equals(primaryKey)) { whereSql += "AND " + key + " = ?, "; } else { setSql += key + "= ?, "; } } } } } setSql = setSql.substring(0, setSql.length() - 2); whereSql = whereSql.substring(0, whereSql.length() - 2); String result = " update " + tableName + setSql + whereSql; return result; } private String genInsertSql(String tableName, Map mapValue) { String columnNames = ""; String columnValues = ""; if (null != mapValue && !mapValue.isEmpty()) { Set set = mapValue.entrySet(); for (Iterator it = set.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String key = ObjectUtils.toString(entry.getKey()).trim() .toLowerCase(); if (null != key && !"".equals(key)) { columnNames += " " + key + ", "; columnValues += " ? , ";//inset value(?,?,?) } } } columnNames = columnNames.substring(0, columnNames.length() - 2); columnValues = columnValues.substring(0, columnValues.length() - 2); String result = "insert into " + tableName + " (" + columnNames + ") values (" + columnValues + ")"; System.out.println("genInsertSql:" + result); return result; } private List<ParamMap> executeListBysql(String sql) throws Exception { return executeListBysql(sql, new HashMap()); } private List<ParamMap> executeListBysql(String sql, Map param) throws Exception { return executeListBysql(sql, param, null); } private List<ParamMap> executeListBysql(String sql, String order) throws Exception { return executeListBysql(sql, null, order); } private List<ParamMap> executeListBysql(String sql, Map param, String orderby) throws Exception { List list = new ArrayList(); Connection conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); if(param != null && param.size() > 0){ int i = 1; for(Object value : param.values()){ stmt.setObject(i, value); i++; } } if (null != orderby) { sql += " " + orderby; } System.out.println(com.micon.base.util.DateUtils.DATEFORMAT_yMd_hms.format(new Date()) +" the final sql = " + sql); ResultSet rs = null; try { rs = stmt.executeQuery(); ResultSetMetaData md = rs.getMetaData(); // 获得该ResultSet中的列数 int columnCount = md.getColumnCount(); // 从前往后的移动结果集指针,处理每条记录 while (rs.next()) { // 每条记录都包含columnCount个列 ParamMap map = new ParamMap(); for (int i = 1; i < columnCount + 1; i++) { // 由于不知道该列的类型,所以用getObject方法获取值 map.put(ObjectUtils.toString(md.getColumnName(i)).trim() .toLowerCase(), rs.getString(i)); } list.add(map); } } catch (SQLException ex) { ex.printStackTrace(); throw new Exception(this.getClass()+",the method of executeListBysql ,详细报错信息:"+ex.getMessage()); } finally { clean(rs, stmt, conn); } System.out.println("--- RESULT_LIST = " +list ); return list; } public Integer querySize(String sql) throws Exception{ List<ParamMap> list = executeListBysql(sql); if(list.size() > 0){ ParamMap paramMap = list.get(0); Object obj = paramMap.entrySet().iterator().next().getValue(); Integer count = Integer.parseInt(obj.toString()); System.out.println(com.micon.base.util.DateUtils.DATEFORMAT_yMd_hms.format(new Date()) +" the sql count = " + sql+" , count = " + count); return count; } return 0; } public Double queryOneField(String sql) throws Exception{ return queryOneField(sql,null); } public Double queryOneField(QueryBean bean) throws Exception{ return queryOneField(bean.getSql(),bean.getQueryMap()); } public Double queryOneField(String sql,Map param) throws Exception{ double count=0.0; List<ParamMap> list = executeListBysql(sql,param); if(list.size() > 0){ ParamMap paramMap = list.get(0); Object obj = paramMap.entrySet().iterator().next().getValue(); if(obj != null){ count= Double.valueOf(obj.toString()); } System.out.println(com.micon.base.util.DateUtils.DATEFORMAT_yMd_hms.format(new Date()) +" the sql count = [ " + sql+" ] , count = " + count); } return count; } public Integer queryOneField2Int(String sql) throws Exception{ return queryOneField2Int(sql,null); } public Integer queryOneField2Int(QueryBean bean) throws Exception{ return queryOneField2Int(bean.getSql(),bean.getQueryMap()); } public Integer queryOneField2Int(String sql,Map param) throws Exception{ int count=0; List<ParamMap> list = executeListBysql(sql,param); if(list.size() > 0){ ParamMap paramMap = list.get(0); Object obj = paramMap.entrySet().iterator().next().getValue(); if(obj != null){ count= Integer.valueOf(obj.toString()); } System.out.println(com.micon.base.util.DateUtils.DATEFORMAT_yMd_hms.format(new Date()) +" the sql count = [ " + sql+" ] , count = " + count); } return count; } // public Integer querySize(QueryBean bean) throws Exception{ // return querySize(bean.getSql(),bean.getQueryMap()); // } public Integer querySize(String sql,Map param) throws Exception{ StringBuffer sqlSb = new StringBuffer(); sqlSb.append("select COUNT(1) cnt from (") .append(sql) .append(") a"); List<ParamMap> list = executeListBysql(sqlSb.toString(),param); if(list.size() > 0){ Integer count = Integer.parseInt(list.get(0).get("cnt").toString()); System.out.println(com.micon.base.util.DateUtils.DATEFORMAT_yMd_hms.format(new Date()) +" the sql count = [ " + sqlSb.toString()+" ] , count = " + count); return count; } return 0; } public List<ParamMap> queryByPage(String sql, Page page) throws Exception { return queryByPage(sql, null, page, null); } public List queryByPage(String sql, Page page, String order) throws Exception { return queryByPage(sql, null, page, order); } public List queryByPage(String sql,Map<String,Object> param ,Page page) throws Exception { return queryByPage(sql, param, page, null); } public List<ParamMap> queryByPage(QueryBean bean, Page page, String order) throws Exception { return queryByPage(bean.getSql(), bean.getQueryMap(), page, order); } public List<ParamMap> queryByPage(String sql, Map<String,Object> param, Page page, String order) throws Exception { System.out.println("page=="+page); if (page == null){ // 如果传入的页面对象为空,则使用默认值 return executeListBysql(sql, param, order); } Integer count = querySize(sql, param); page.setTotalCount(count); if (null == order) { order = " order by id "; } StringBuffer sqlSb = new StringBuffer(); sqlSb.append("select * "); sqlSb.append(" from (select a.* ").append(", row_number() over(").append(order).append(") as R"); sqlSb.append(" from (").append(sql).append(") a ) b "); sqlSb.append(" where R > ").append(page.getPreviousPageNumber()*page.getPageSize()); sqlSb.append(" and R <= ").append(page.getPageNumber()*page.getPageSize()); System.out.println(com.micon.base.util.DateUtils.DATEFORMAT_yMd_hms.format(new Date()) +" the page sql = " + sqlSb); return executeListBysql(sqlSb.toString(), param); } public List queryListBySql(String sql, Map<String,Object> param) throws Exception { return queryListBySql(sql, param,null); } public List queryListBySql(String sql) throws Exception { return queryListBySql(sql,null,null); } public List queryListBySql(QueryBean bean,String order) throws Exception { return queryListBySql(bean.getSql(),bean.getQueryMap(),order); } public List queryListBySql(QueryBean bean) throws Exception { return queryListBySql(bean.getSql(),bean.getQueryMap(),null); } public List queryListBySql(String sql,String order) throws Exception { return queryListBySql(sql,null,order); } public List queryListBySql(String sql, Map<String,Object> param,String order) throws Exception { if (null != order && !"".equals(order)) { sql += " " + order + " "; } System.out.println(com.micon.base.util.DateUtils.DATEFORMAT_yMd_hms.format(new Date()) +" the queryListBySql = " + sql); return executeListBysql(sql, param); } public ParamMap queryOneBySql(String sql) throws Exception{ List<ParamMap> list = queryListBySql(sql); if(list.size() > 0){ return list.get(0); } return new ParamMap(); } protected void clean(ResultSet rs, Statement stmt, Connection conn) throws SQLException { try { if (rs != null) { try{ rs.close(); }catch (Exception e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (Exception e) { e.printStackTrace(); } } if (conn != null) { this.releaseConnection(conn); } } catch (SQLException e) { e.printStackTrace(); System.out.println("error in clean(rs,ps,conn)" + e); throw new SQLException(e.toString()); } } public void clean(Statement ps, Connection conn) throws SQLException { if (ps != null) { try { ps.close(); } catch (SQLException ex) { throw new SQLException(ex.toString()); } finally { if (conn != null) { this.releaseConnection(conn); } } } if (conn != null) { this.releaseConnection(conn); } } /** * 释放连接 * @param conn * @throws SQLException */ public void releaseConnection(Connection conn) throws SQLException { try { if (conn == null || conn.isClosed()) { return; } conn.close(); } catch (SQLException ex) { ex.printStackTrace(); System.out.println("Error occrued when releaseConnection connection" + ex); throw new SQLException(ex.getMessage()); } } public static void main(String[] args) throws Exception { // System.out.println(getJdbcUtils().getConnection()); // Map<String, Object> paramMap = new HashMap<String, Object>(); // paramMap.put("id",4); // paramMap.put("menu",0); // StringBuffer sb = new StringBuffer(); // sb.append("select * from s_auth where 1= 1 "); // jdbcUtils.getJdbcUtils().getConnection().createStatement().addBatch(sql) // String sql = "select * from s_user where name = ? and psw = ? "; //// // Map map = new LinkedHashMap(); // // map.put("name", "micon"); // map.put("psw", "111"); // // // List<Map<String, Object>> list = jdbcUtils.getJdbcUtils().queryListBySql(sql,map); // for(Map<String, Object> param : list){ // System.out.println("param = "+param); //// System.out.println("-----------------------------------------"); //// System.out.println("id = "+ param.get("id").toString()); //// System.out.println("name = "+ param.get("name").toString()); // } // // Map insertMap = new HashMap(); // insertMap.put("create_date", new Date()); // // jdbcUtils.getJdbcUtils().insert("s_user", insertMap); java.sql.Date sqlDate = com.micon.base.util.DateUtils. getSqlDateWithYmdHms(com.micon.base.util.DateUtils.DATEFORMAT_yMd_hms.format(new Date())); Map<String, Object> param = new HashMap<String, Object>(); param.put("name", "micon-6"); param.put("age", "1"); param.put("create_date", new Date()); jdbcUtils.getJdbcUtils().insert("micon", param); // System.out.println("insert success !"); // Map params = new HashMap(); // params.put("menu", 0); // String sql = "select * from s_auth where 1=1 "; // List<Map<String, Object>> list = jdbcUtils.getJdbcUtils().queryListBySql(sql, params, " order by level"); // System.out.println("resutl list = "+list); } }
相关推荐
JDBC封装的工具类,将所有共同的代码提取过来,形成工具类
jdbc封装(实现对实体的增删改查[分页]),辅助学习Hibernate 包含三个文件夹,分别是: code-access实现 是用access实现的,本意是access方便,就一个文件,方便部署。但access有好多不支持,就写成这样.主要是可参考Dao...
文档脉络清楚的详述了实现JDBC封装所需要进行的步骤。
标题:JDBC封装类 描述:此文章将详细介绍一个用于简化Java中JDBC操作的封装类,该类通过提供一系列方法来加速数据库编程任务,包括建立数据库连接、执行查询、处理结果集以及执行更新操作。 ### 一、JDBC封装类...
jdbc封装工具类,此类事封装成list,Object>>格式,可直接把转换为jsonArray格式传输数据。
【标题】:JDBC封装包 【描述】:JDBC(Java Database Connectivity)是Java语言中用来规范客户端程序如何访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。这个封装包是我个人制作的,旨在简化...
"JDBC封装"是指将常见的数据库操作,如增删改查(CRUD:Create, Read, Update, Delete),进行模块化和抽象化的过程,以便于在代码中重复使用和简化数据库交互。下面将详细介绍JDBC封装的原理、步骤以及它带来的好处...
Java JDBC封装类升级版,带增删改查例子,支持oracle,MySql,hsqldb 等,支持事务,返回数据格式 支持二维数组,MAP格式,以及javabean对象。有利于初学者DbDemo.java为demo,Connect为jdbc封装类,可以作为项目共通类...
**标题:“自己写个JDBC封装”** 在Java开发中,JDBC(Java Database Connectivity)是连接Java应用程序和关系数据库的标准接口。然而,原始的JDBC API使用起来相对繁琐,需要编写大量的重复代码,例如建立数据库...
"java增删改查JDBC封装类(泛型封装)"这个主题是关于如何利用泛型来优化JDBC操作,以提高代码的可读性、安全性和复用性。以下将详细讲解这个主题涉及的知识点。 1. **JDBC基础**: - JDBC是Java中连接数据库的标准...
"jdbc-utils.rar_Utils_jdbc_jdbc封装"这个压缩包提供了一些工具类,用于简化JDBC操作,提高代码的可读性和可维护性。下面我们将详细探讨JDBC封装处理类的原理和实现。 1. **JDBC基础** - JDBC API包括一组Java...
Scweery 是 Scala 一个封装了 JDBC 操作用来从 SQL 中创建 Scala 对象的工具包。 示例代码: using(petsDB) { connection => val findHogsQuery = "select name, gender from pets where family='erinaceidae' ...
本压缩包“DB.rar_jdbc封装”显然是一个关于如何使用Java JDBC进行数据库连接封装的示例或教程。下面我们将详细探讨JDBC以及如何进行封装。 首先,JDBC是Java平台上的一个接口,它允许Java应用程序与各种数据库进行...
在实际应用中,这些步骤往往重复且繁琐,因此进行JDBC封装是提高代码复用性和减少错误的有效方式。 1. **加载驱动**: 在Java程序中,我们需要通过Class.forName()方法加载对应的数据库驱动。封装时,我们可以将...
标题提到的"类似hibernate的jdbc封装"就是这样的一个实践,它试图在不引入庞大框架的情况下,提供类似Hibernate的便捷性。 首先,我们来了解JDBC(Java Database Connectivity),它是Java中用于连接数据库的标准...
Java JDBC封装类,带增删改查例子,支持oracle,MySql,hsqldb 等,支持事务,返回数据格式 支持二维数组,MAP格式,以及javabean对象。有利于初学者DbDemo.java为demo,Connect为jdbc封装类,可以作为项目共通类使用。
本项目中,"自己封装的小框架--JDBC封装 Action层封装 手动事务管理"是一个实用的实践案例,旨在提高开发效率,优化代码结构,并确保数据操作的完整性。下面我们将深入探讨这个框架中的主要组成部分及其相关知识点。...
在JDBC封装中,反射非常有用,因为它允许在运行时创建和执行SQL语句,而不必在代码中硬编码具体的数据库操作。例如,你可以使用反射来获取类的字段信息,然后动态生成对应的SET和WHERE子句,以此实现通用的CRUD...
总之,JDBC封装是Java Web开发中的常见实践,它提高了代码的可读性和可维护性,减少了错误发生的可能性。在实际项目中,我们还应该结合使用数据库连接池、DAO模式以及事务管理等技术,以实现更高效、安全的数据库...