当前位置:首页 > 开发 > 编程语言 > 数据库连接池 > 正文

dbcp 数据库连接池配置及对数据库的增、删、改、查

发表于: 2015-01-27   作者:caixu52110   来源:转载   浏览次数:
摘要: 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; impor
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();
		}
	}
}

 

dbcp 数据库连接池配置及对数据库的增、删、改、查

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
SQLite数据库是android系统自带的数据库,小巧使用方便。 最常见的就是电话簿。电话簿数据库存在的
1、解压附件,双击 Html_conDB.html文件可以查看效果;以下是实现功能的部分JS代码。 var db="Datab
原文链接:http://www.cnblogs.com/moshengren/archive/2010/10/19/1855322.html 打开数据库 的操作
本文将演示如何通过 Entity Framework 数据模型创建、修改、删除数据库记录。 插入 为了在数据库里
ASP.NET3.5中包含了新的数据绑定控件--ListView,这是一个类似与repeater与gridview结合的控件,可
首先要创建一个类,继承自SQLiteOpenHelper,用来打开数据库   package com.SQLiteTest2;   imp
首先要创建一个类,继承自SQLiteOpenHelper,用来打开数据库   package com.SQLiteTest2;   imp
上篇博客利用Hibernate搭建起一个简单的例子,把数据库的映射显示了出来在上一篇的博客基础上这篇博
一、Hibernate框架简介 Hibernate是一个优秀的Java持久化层解决方案,是当今主流的对象-关系映射(O
最近在学习Oracle数据库,其实在我看来初级的数据库还是很简单的,其实简单的数据库无疑就是4个字:
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号