⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbmanager.java

📁 this is very useful book for the learn of java programing.
💻 JAVA
字号:
package edu.buptsse.sxjd.dao;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;
import edu.buptsse.sxjd.service.BusinessException;


public class DBManager {
	private static DataSource ds = null;

	/**
	 * 取得可用数据库连接
	 * @return
	 * @throws BusinessException
	 */
	public static Connection GetConnection() throws BusinessException{
		Connection conn;
		try {
			conn = ds.getConnection();
			conn.setAutoCommit( false);
		} catch (SQLException e) {
			e.printStackTrace();
			BusinessException be= new BusinessException();
			be.setMessageKey("conn.getfailure");
			throw be;
		}
		return conn;
	}
	

	/**
	 * 提交事务
	 * @param conn
	 * @throws BusinessException
	 */
	public static void Commit(Connection conn) throws BusinessException
	{
		checkAutoCommit(conn);
		try {
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			BusinessException be= new BusinessException();
			be.setMessageKey("conn.commitfailure");
			throw be;
		}
	}
	
	/**
	 * 回滚事务
	 * @param conn
	 * @throws BusinessException
	 */
	public static void Rollback(Connection conn) throws BusinessException 
	{
		try {
			conn.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
			BusinessException be= new BusinessException();
			be.setMessageKey("conn.roolbackfailure");
			throw be;
		}
	}
	
	/**
	 * 检测数据库连接是不是autocommit
	 * @param conn
	 * @return
	 * @throws BusinessException
	 */
	public static boolean checkAutoCommit(Connection conn) throws BusinessException
	{
		if(null==conn){
			BusinessException be= new BusinessException();
			be.setMessageKey("conn.isnull");
			throw be;
		}
			
		try {
			if (conn.getAutoCommit()){
				BusinessException be= new BusinessException();
				be.setMessageKey("conn.isautocommit");
				throw be;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			BusinessException be = new BusinessException();
			be.setMessageKey("conn.isautocommit");
			throw be;
		}
		return true;
	}
	
	/**
	 * 关闭数据库连接
	 * @param conn
	 */
	public static void close(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			conn = null;
		}
	}
	
	public static DataSource getDs() {
		return ds;
	}

	public static void setDs(DataSource datasourse) {
		if (null == ds)
			DBManager.ds = datasourse;
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -