package com.pro.lottery.util; import java.lang.reflect.Field; import java.sql.CallableStatement; 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.List; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.DataSourceConnectionFactory; import com.pro.lottery.modle.UserTable; /*** * @description: 数据库连接池配置及存储过程调用 * @author Caixu * @dateTime 2014-11-27 * */ public class DataSourceFactory { private static BasicDataSource dbcp; private static DataSourceConnectionFactory dscf; String className = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; String url = "jdbc:sqlserver://localhost:1433;database=PEpos"; String userName = "sa"; String password = "woaixua52110"; /* * String className = "oracle.jdbc.driver.OracleDriver"; String url = * "jdbc:oracle:thin:@172.27.35.2:1521:orcl"; String userName = "scott"; * String password = "tiger"; */ private DataSourceFactory() { dbcp = new BasicDataSource(); dbcp.setDriverClassName(className); dbcp.setUrl(url); dbcp.setUsername(userName); dbcp.setPassword(password); // 最大获取连接数 dbcp.setMaxActive(100); // 最大可用空闲连接数 dbcp.setMaxIdle(10); dbcp.setMaxWait(6000); dscf = new DataSourceConnectionFactory(dbcp); } private static DataSourceFactory Pool; public synchronized static DataSourceFactory getInstance() { if (Pool == null) { Pool = new DataSourceFactory(); } return Pool; } public Connection getConnection() { Connection con = null; try { con = dscf.createConnection(); } catch (Exception e) { e.printStackTrace(); } return con; } /** * 调用存储过程执行 insert update delete操作 * * @param procedureName * 存储过程名 * @param obj * 存储过程参数 * @return */ public int update(String procedureName, Object[] obj) { Connection connection = null; CallableStatement cstmt = null; try { DataSourceFactory pool = DataSourceFactory.getInstance(); connection = pool.getConnection(); // 得到拼接的存储和参数 String proStr = getProcedureStr(procedureName, obj); cstmt = connection.prepareCall(proStr); for (int i = 0; i < obj.length; i++) { cstmt.setObject(i + 1, obj[i]); } cstmt.execute(); int count = cstmt.getUpdateCount(); return count; } catch (Exception e) { e.printStackTrace(); return -1; } finally { close(connection, cstmt, null); } } /** * 批量执行存储过程 如果出现异常则不会提交事务 * @param procedureNames * @param objs * @return */ public int batchUpdateByProcedure(String[] procedureNames, List<Object[]> objs){ Connection connection = null; CallableStatement cstmt = null; try { if(procedureNames.length != objs.size()){ return -1; } DataSourceFactory pool = DataSourceFactory.getInstance(); connection = pool.getConnection(); connection.setAutoCommit(false); boolean flag = false; int resCount = 0; for(int j=0; j<objs.size(); j++){ // 得到拼接的存储和参数 String proStr = getProcedureStr(procedureNames[j], objs.get(j)); cstmt = connection.prepareCall(proStr); for (int i = 0; i < objs.get(j).length; i++) { cstmt.setObject(i + 1, objs.get(j)[i]); } cstmt.execute(); int count = cstmt.getUpdateCount(); resCount = resCount + count; if(count == 0){ flag = true; resCount = 0; break; } } //如果有一个失败 则回滚 if(flag){ connection.rollback(); } connection.commit(); return resCount; } catch (Exception e) { e.printStackTrace(); return -1; } } /** * sql语句的批处理 * * @param sqlArray * @return */ public int batchUpdateBySql(String[] sqlArray) { Connection connection = null; Statement st = null; try { DataSourceFactory pool = DataSourceFactory.getInstance(); connection = pool.getConnection(); st = connection.createStatement(); for (String sql : sqlArray) { st.addBatch(sql); } } catch (Exception e) { e.printStackTrace(); return -1; } // 取消自动提交 try { //是否回滚 boolean flag = false; connection.setAutoCommit(false); int[] count = st.executeBatch(); int resCount = 0; for (int i : count) { resCount = resCount + i; if(i == 0){ flag = true; resCount = 0; break; } } //如果有一个失败 则回滚 if(flag){ connection.rollback(); } connection.commit(); return resCount; } catch (Exception e) { e.printStackTrace(); // 如果出错了,则应该把数据回滚 try { connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } return -1; }finally { close(connection, st, null); } } /** * 拼接程储过程 * @param procedureName * @param obj * @return */ public static String getProcedureStr(String procedureName, Object[] obj) { StringBuffer proStr = new StringBuffer(); proStr.append("{call " + procedureName + "("); for (Object objStr : obj) { proStr.append("?").append(","); } String temp = ""; if (obj.length == 0) { temp = proStr.toString(); } else { temp = proStr.substring(0, proStr.length() - 1); } temp = temp + ")}"; return temp; } /** * 查询行记录 * * @param sql * @return */ public long findCount(String sql) { long result = -1; Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { DataSourceFactory pool = DataSourceFactory.getInstance(); con = pool.getConnection(); ps = con.prepareStatement(sql); rs = ps.executeQuery(); if (rs.next()) { result = rs.getLong(1); } } catch (Exception e) { e.printStackTrace(); } finally { close(con, ps, rs); } return result; } /** * 执行返回泛型集合的SQL语句 * * @param cls * 泛型类型 * @param sql * 查询SQL语句 * @return 泛型集合 */ public <T> List<T> getObjectListBySql(Class<T> cls, String sql) { List<T> list = new ArrayList<T>(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { DataSourceFactory pool = DataSourceFactory.getInstance(); con = pool.getConnection(); ps = con.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { T obj = executeResultSet(cls, rs); list.add(obj); } } catch (Exception e) { e.printStackTrace(); } finally { close(con, ps, rs); } return list; } /** * 执行数据的SQL语句 此方法不用写实体类 * * @param cls * 泛型类型 * @param sql * 查询SQL语句 * @return 泛型集合 */ public List<Object[]> getObjectListBySql_fields(String sql) { List<Object[]> list = new ArrayList<Object[]>(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String temp = sql.trim().substring("select".length(), sql.indexOf("from")); String[] fields = temp.split(","); try { DataSourceFactory pool = DataSourceFactory.getInstance(); con = pool.getConnection(); ps = con.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { Object[] obj = executeResultSet(fields, rs); list.add(obj); } } catch (Exception e) { e.printStackTrace(); } finally { close(con, ps, rs); } return list; } /** * 执行返回泛型类型对象的SQL语句 * * @param cls * 泛型类型 * @param sql * SQL语句 * @return 泛型类型对象 */ public <T> T getObejectBySql(Class<T> cls, String sql) { T obj = null; Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { DataSourceFactory pool = DataSourceFactory.getInstance(); con = pool.getConnection(); ps = con.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { obj = executeResultSet(cls, rs); break; } } catch (Exception e) { e.printStackTrace(); } finally { close(con, ps, rs); } return obj; } /** * 将一条记录转成一个对象 * * @param cls * 泛型类型 * @param rs * ResultSet对象 * @return 泛型类型对象 * @throws InstantiationException * @throws IllegalAccessException * @throws SQLException */ private <T> T executeResultSet(Class<T> cls, ResultSet rs) throws InstantiationException, IllegalAccessException, SQLException { T obj = cls.newInstance(); ResultSetMetaData rsm = rs.getMetaData(); int columnCount = rsm.getColumnCount(); // Field[] fields = cls.getFields(); Field[] fields = cls.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; String fieldName = field.getName(); String fieldType = field.getType().toString(); for (int j = 1; j <= columnCount; j++) { String columnName = rsm.getColumnName(j); if (fieldName.equalsIgnoreCase(columnName)) { Object value = rs.getObject(j); //解决空指针问题 if (value == null && ("int".equals(fieldType) || "long".equals(fieldType) || "double".equals(fieldType) || "float".equals(fieldType))) { value = 0; } field.setAccessible(true); field.set(obj, value); break; } } } return obj; } /** * 将一条记录转成一个数据 * @param cls * 泛型类型 * @param rs * ResultSet对象 * @return 泛型类型对象 * @throws InstantiationException * @throws IllegalAccessException * @throws SQLException */ @SuppressWarnings("unused") private Object[] executeResultSet(String[] fields, ResultSet rs) throws SQLException { Object[] obj = new Object[fields.length]; ResultSetMetaData rsm = rs.getMetaData(); int columnCount = rsm.getColumnCount(); // Field[] fields = cls.getFields(); //Field[] fields = cls.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { String fieldName = fields[i].trim(); for (int j = 1; j <= columnCount; j++) { String columnName = rsm.getColumnName(j); if (fieldName.equalsIgnoreCase(columnName)) { Object value = rs.getObject(j); obj[i] = value; break; } } } return obj; } /** * 执行返回泛型集合的存储过程 * * @param procedureName * 存储过程名 * @param obj * 存储过程参数 * @return */ public <T> List<T> getObjListByProcedure(Class<T> cls, String procedureName, Object[] object) { List<T> list = new ArrayList<T>(); Connection con = null; CallableStatement cstmt = null; ResultSet rs = null; try { DataSourceFactory pool = DataSourceFactory.getInstance(); con = pool.getConnection(); // 得到拼接的存储和参数 String proStr = getProcedureStr(procedureName, object); cstmt = con.prepareCall(proStr); for (int i = 0; i < object.length; i++) { cstmt.setString(i + 1, (String) object[i]); } rs = cstmt.executeQuery(); while (rs.next()) { T obj = executeResultSet(cls, rs); list.add(obj); } return list; } catch (Exception e) { e.printStackTrace(); return null; } finally { close(con, cstmt, rs); } } /** * 关闭JDBC对象,释放资源。 * * @param con * 连接对象 * @param ps * 命令对象 * @param rs * 结果集对象 */ private static void close(Connection con, Statement ps, ResultSet rs) { try { if (rs != null) { rs.close(); rs = null; } if (ps != null) { ps.close(); ps = null; } if (con != null) { con.close(); con = null; } } catch (SQLException e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { Statement sm = null; ResultSet rs = null; try { /* * DataSourceFactory pool = DataSourceFactory.getPool(); Connection * connection = pool.getConnection(); System.out.println("dfad"); sm * = connection.createStatement(); rs = * sm.executeQuery("select * from lotteryInfo"); while (rs.next()) { * System.out.println(rs.getString(1)); * System.out.println(rs.getString(2)); * System.out.println(rs.getString(4)); * System.out.println(rs.getString(5)); } */ /* * List<ReqLottery> list = DataSourceFactory.getListObject( * ReqLottery.class, "select * from lotteryInfo"); for (ReqLottery * reqLottery : list) { * System.out.println(reqLottery.getLotteryDate()); * System.out.println(reqLottery.getLotteryId()); * System.out.println(reqLottery.getLotteryIssue()); * System.out.println(reqLottery.getLotteryNum()); * System.out.println(reqLottery.getLotteryType()); } */ /* * long count = * DataSourceFactory.findCount("select count(*) from lotteryinfo"); * System.out.println(count); */ /* * List<ReqLottery> list = DataSourceFactory.getObjList( * ReqLottery.class, "LOTTERYINFO_FINDLOTTERYINFO_FIND", new * Object[]{"1001"}); for (ReqLottery reqLottery : list) { * System.out.println(reqLottery.getLotteryDate()); * System.out.println(reqLottery.getLotteryId()); * System.out.println(reqLottery.getLotteryIssue()); * System.out.println(reqLottery.getLotteryNum()); * System.out.println(reqLottery.getLotteryType1()); } */ /* * List<UserTable> list = * DataSourceFactory.getObjList(UserTable.class, * "select * from UserTable"); for (UserTable u : list) { * System.out.println(u.getId()); System.out.println(u.getAge()); * System.out.println(u.getName()); System.out.println(u.getSex()); * } */ /*String[] sqlArray = { "update dept set deptCount = 20 where deptId = 1", "update UserTable set age = 20" }; int count = DataSourceFactory.batchUpdateBySql(sqlArray); System.out.println("成功了多少条:" + count);*/ /*String[] proName = {"TEST_BATCH_1","TEST_BATCH_2"}; List<Object[]> objs = new ArrayList<Object[]>(); objs.add(new Object[]{1}); objs.add(new Object[]{5}); int count = DataSourceFactory.batchUpdateByProcedure(proName, objs); System.out.println("成功了多少条:" + count);*/ String[] fields = {"id", "name", "sex", "age"}; List<Object[]> lists = DataSourceFactory.getInstance().getObjectListBySql_fields("select id, name, sex, age from UserTable"); for (Object[] objects : lists) { for (Object object : objects) { System.out.print(object+" "); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } }
相关推荐
1. **添加依赖**:在项目中引入DBCP的JAR包,如描述中所提到的"DBCP数据库连接池的完整jar包"。 2. **配置连接池**:创建一个配置文件,设置数据库URL、用户名、密码、驱动类名以及DBCP特定的参数。 3. **初始化...
**数据库连接池(DBCP)** 是一个在Java应用程序中管理数据库连接的工具,它能够有效地提高数据库操作的性能和效率。DBCP全称为`Jakarta Commons DBCP`,是Apache软件基金会的一个项目,提供了对数据库连接的池化...
5. **增删改查操作**: 获取到数据库连接后,就可以进行标准的JDBC操作,如使用Statement或PreparedStatement执行SQL,处理ResultSet等。例如,插入一条记录: ```java PreparedStatement pstmt = conn.prepare...
总的来说,DBCP数据库连接池是Java应用程序中提高数据库访问效率的重要工具,通过合理配置和使用,可以显著优化数据库操作性能,降低系统资源消耗。在实际项目中,根据具体需求选择合适的数据库连接池组件,对于提升...
综上所述,DBCP数据库连接池是Java Web开发中常用的一种数据库连接管理工具,通过合理的配置和使用,可以显著提高应用的性能和稳定性。在实际项目中,结合Spring等框架,可以更便捷地管理和使用数据库连接。确保正确...
"DBCP数据库连接池jar包.zip"这个压缩包包含以下文件: 1. `commons-dbcp2-2.6.0-bin`:这是DBCP2的二进制发行版,包含了编译后的jar文件,可以直接在项目中引用,用于实现数据库连接池的功能。 2. `commons-pool2-...
DBCP(DataBase Connection Pool)是Apache组织提供的一款Java数据库连接池组件,它是Tomcat服务器默认使用的连接池组件。数据库连接池技术的主要目的是提高系统性能,减少数据库操作中的资源开销,通过预先创建并...
2. `commons-dbcp-1.4.jar`: 这就是DBCP的主要库文件,包含了数据库连接池的实现。它提供了BasicDataSource类,这是一个符合JDBC DataSource接口的数据源,可以配置连接池的各种参数,如最大连接数、最小连接数、...
DBCP(Database Connection Pool)是Apache软件基金会的一个开源项目,全称为Apache Commons DBCP,它是一个基于Java的数据库连接池实现。在Java应用程序中,DBCP被广泛用于管理数据库连接,以提高性能和资源利用率...
Apache DBCP(Database ...总结来说,Apache DBCP是一个实用且基础的数据库连接池实现,适合对性能要求不那么高,但需要进行数据库连接管理的Java应用。通过合理配置和使用,可以有效地提升应用的效率和稳定性。
随着`commons-dbcp2`的版本更新,数据库连接池的配置也有了相应的调整。为了更好地理解和配置这些参数,本文将详细解析`commons-dbcp2`中的一些关键参数及其意义。 #### 1. `maxIdle` - **参数描述**:表示连接池中...
NULL 博文链接:https://xiongjiajia.iteye.com/blog/1295094
使用DBCP数据库连接池,你需要在你的Java项目中引入这三个JAR文件,并进行相应的配置。以下是一些基本配置步骤: 1. 将这三个JAR文件添加到项目的类路径中。 2. 创建一个XML配置文件(如`dbcp-config.xml`),定义...
在上述内容中,主要展示了如何配置和使用DBCP数据库连接池。首先,配置文件`config.xml`定义了两个不同的数据库连接池,每个池都有自己的名称、用户名、密码、数据库URL、最大连接数和等待时间。例如,`one`连接池...
在Java中配置DBCP数据库连接池涉及以下几个关键知识点: 1. **依赖引入**:首先,你需要在项目中引入DBCP的相关库。在Maven项目中,可以在pom.xml文件中添加如下依赖: ```xml <groupId>commons-dbcp ...
DBCP,全称为Apache Database Connection Pool,是由Apache软件基金会开发的一款开源数据库连接池组件。它在Java应用程序中扮演着至关重要的角色,通过有效地管理和复用数据库连接,显著提高了数据库访问性能,同时...
DBCP(DataBase connection pool),数据库连接池。是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。单独使用dbcp需要3个包:commons-dbcp.jar,commons-pool.jar,commons-collections.jar由于建立...