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

📄 database.java

📁 一个jsp的oa系统,里面有很多亮点学习!
💻 JAVA
字号:
package com.oa.lp.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.PropertyResourceBundle;

public class DataBase {
	/**
	 * 数据库访问URL
	 */
	private static String url;

	/**
	 * 数据库驱动
	 */
	private static String driver;

	/**
	 * 数据库访问用户名
	 */
	private static String username;

	/**
	 * 数据库访问口令
	 */
	private static String password;
	/**
	 * 配置文件名称
	 */
	private final static String fileName = "database";
	
	private static ThreadLocal connection = new ThreadLocal();

	static {
		config();
	}

	private static void config() {
		//读取系统配置
		PropertyResourceBundle resourceBundle = (PropertyResourceBundle) PropertyResourceBundle
				.getBundle(fileName);
		//将系统设置赋值给类变量
		Enumeration enu = resourceBundle.getKeys();
		while (enu.hasMoreElements()) {
			String propertyName = enu.nextElement().toString();
			if (propertyName.equals("database.url"))
				url = resourceBundle.getString("database.url");
			if (propertyName.equals("database.driver"))
				driver = resourceBundle.getString("database.driver");
			if (propertyName.equals("database.username"))
				username = resourceBundle.getString("database.username");
			if (propertyName.equals("database.password"))
				password = resourceBundle.getString("database.password");
		}
	}
	
	/**
	 * 取得数据库连接
	 * @return
	 * @throws SQLException
	 */
	public synchronized static java.sql.Connection getConnection()
			throws SQLException {
		Connection con = (Connection) connection.get();
		if (con != null && !con.isClosed()) {
			return con;
		}
		//直接使用JDBC驱动连接
		try {
			Class providerClass = Class.forName(driver);
			con = DriverManager.getConnection(url, username,
						password);
			con.setAutoCommit(false);
			connection.set(con);
			return con;

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static void commit() {
		Connection con = (Connection) connection.get();
		try {
			con.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void rollback() {
		Connection con = (Connection) connection.get();
		try {
			con.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public synchronized static void releaseConnection(Connection con) {

		try {
			if (con != null && !con.isClosed())
				con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		con = null;
	}
	public static void main(String[] args) {
		
		try {
			DataBase.getConnection();
			System.out.println("OK");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}	
}

⌨️ 快捷键说明

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