博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
DBActionByMap
阅读量:6876 次
发布时间:2019-06-26

本文共 5817 字,大约阅读时间需要 19 分钟。

  hot3.png

package org.tips.dao;import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.math.BigDecimal;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.xml.parsers.ParserConfigurationException;import org.apache.commons.dbcp.BasicDataSource;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.tips.dao.config.DomParseService;import org.xml.sax.SAXException;/*** * 数据库增删查改通用类 已注入dataSource *  * @author tips *  */public class DBActionByMap {	protected static Log logger = LogFactory.getLog(DBActionByMap.class);	private BasicDataSource dataSource;	private Connection conn;	public DBActionByMap() {	}	public BasicDataSource getDataSource() {		return dataSource;	}	public void setDataSource(BasicDataSource dataSource) {		this.dataSource = dataSource;	}	/**	 * 初始化,设置数据库是否自动提交	 * 	 * @param autoCommit	 *            true-自动提交	 * @return	 * @throws SQLException	 */	public void initialization(boolean autoCommit) throws SQLException {		conn = this.dataSource.getConnection();		conn.setAutoCommit(autoCommit);	}	/***	 * 通过SQL查询数据,返回List	 * 	 * @param sql	 * @param params	 * @param c	 * @return	 * @throws SQLException	 * @throws IllegalAccessException	 * @throws InstantiationException	 * @throws InvocationTargetException	 * @throws IllegalArgumentException	 * @throws Exception	 */	public 
List
findBySql(String sqlMap, HashMap
params, Class
c) throws SQLException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (conn == null || conn.isClosed()) { this.initialization(true); } String sql = this.getSQL(sqlMap); List
list = new ArrayList
(); /** * 取出c的这个对象中有多少个方法 */ Method[] ms = c.getMethods(); PreparedStatement ps = conn.prepareStatement(sql.replaceAll("#+[A-Za-z0-9_]+#", "?")); this.doParams(ps, params, this.parseSQL(sql)); ResultSet rs = ps.executeQuery(); /** * 得到db中的表的列 */ ResultSetMetaData rsmd = rs.getMetaData(); /** * 存储全部的列名 */ String[] columnname = new String[rsmd.getColumnCount()]; for (int i = 0; i < columnname.length; i++) { columnname[i] = rsmd.getColumnName(i + 1); } while (rs.next()) { T t = c.newInstance(); // t.setId(rs.getInt("id")); for (int i = 0; i < columnname.length; i++) { String cn = columnname[i]; cn = "set" + cn.substring(0, 1).toUpperCase() + cn.substring(1).toLowerCase(); for (Method m : ms) { if (m.getName().equals(cn)) { if (rs.getObject(columnname[i]) != null) { if ("java.sql.Timestamp".equals(rs .getObject(columnname[i]).getClass() .getName())) { m.invoke(t, rs.getString(columnname[i])); } else if ("java.math.BigDecimal".equals(rs .getObject(columnname[i]).getClass() .getName())) { m.invoke(t, rs.getBigDecimal(columnname[i])); } else if ("java.sql.Date".equals(rs .getObject(columnname[i]).getClass() .getName())) { m.invoke( t, new java.util.Date(rs.getDate( columnname[i]).getTime())); } else { m.invoke(t, rs.getObject(columnname[i])); } } else { m.invoke(t, rs.getObject(columnname[i])); } break; } } } list.add(t); } return list; } /*** * 通过SQL更新数据 * * @param sql * @param params * @return * @throws SQLException */ public
int doUpdate(String sqlMap, HashMap
params) throws SQLException { if (conn == null || conn.isClosed()) { this.initialization(true); } String sql = this.getSQL(sqlMap); int i = 0; PreparedStatement ps = conn.prepareStatement(sql.replaceAll("#+[A-Za-z0-9_]+#", "?")); doParams(ps, params,this.parseSQL(sql)); i = ps.executeUpdate(); return i; } /** * 通过SQL查询数据,返回数据集 * * @param sql * @param params * @return 数据集 * @throws SQLException */ public ResultSet RsBySql(String sqlMap, HashMap
params) throws SQLException { if (conn == null || conn.isClosed()) { this.initialization(true); } String sql = this.getSQL(sqlMap); PreparedStatement ps = conn.prepareStatement(sql.replaceAll("#+[A-Za-z0-9_]+#", "?")); this.doParams(ps, params,this.parseSQL(sql)); ResultSet rs = ps.executeQuery(); return rs; } /** * 关闭数据库连接对象 * * @param i * 大于0则提交,否则回滚 */ public void closeAll(int i) { try { if (this.conn != null && !this.conn.isClosed()) { if (i > 0) { this.conn.commit(); } else { this.conn.rollback(); } this.conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } } /** * 获取sql * * @param sqlMap * @return */ private String getSQL(String sqlMap) { String sql = null; try { sql = DomParseService.getSQL(sqlMap); } catch (ParserConfigurationException e) { logger.error(e); } catch (SAXException e) { logger.error(e); } catch (IOException e) { logger.error(e); } return sql; } /*** * 解析sql * @param sql * @return */ private HashMap
parseSQL(String sql) { HashMap
hash = new HashMap
(); Pattern p = Pattern.compile("#+[A-Za-z0-9]+#"); Matcher matcher = p.matcher(sql); String value = null; int index=0; while(matcher.find()){ value = matcher.group(); value = value.replace("#", ""); hash.put(String.valueOf(index), value); index++; } /*** int i = 0; int index = 0; while (index != -1) { index = sql.indexOf("#"); sql = sql.substring(index + 1); int index2 = sql.indexOf("#"); if (index2 != -1) { hash.put(i + "", sql.substring(0, index2)); sql = sql.substring(index2 + 1); } i++; } ***/ return hash; } /** * 设置预编译对象参数 * * @param pstmt * @param params * @throws SQLException */ private
void doParams(PreparedStatement pstmt, HashMap
params,HashMap
hash) throws SQLException { if(pstmt!=null && params!=null && hash!=null){ for(int i=0;i

转载于:https://my.oschina.net/scotts/blog/115926

你可能感兴趣的文章
用 zabbix 监测 snmptrap 的主动告警功能
查看>>
HDU1717 小数化分数2
查看>>
delphi 导入excel
查看>>
Linux下 FTP 常见错误 500 530等错误解决方法
查看>>
oracle asm
查看>>
VC基于单文档opengl框架
查看>>
openSUSE13.2安装ruby和rails
查看>>
python 高级函数
查看>>
F.Cards with Numbers
查看>>
简单入门Buffer
查看>>
Paint House II
查看>>
测试评审清单
查看>>
字节流数据的写出(输出)和读取(输入)
查看>>
OO第四阶段总结
查看>>
javascript总结02
查看>>
创建windows服务
查看>>
KSQL日期字段访问
查看>>
HTML5 入门基础
查看>>
Laravel 中的 Many-To-Many
查看>>
Codeforces 371C Hamburgers(二分基础题)
查看>>