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

📄 connectionutil.java

📁 办公自动化项目
💻 JAVA
字号:
package hong.javanet.dao;

import java.util.*;
import java.sql.*;
import org.apache.log4j.Logger;
import java.io.*;

public class ConnectionUtil {

  private static Logger log = Logger.getLogger(ConnectionUtil.class);
  public static final ThreadLocal current = new ThreadLocal();

  private static Properties dbproperties;

  /**
   * 获得当前线程数据库连接
   * @return Connection
   */
  public static Connection currentConnection() {
    Connection conn = (Connection) current.get();
    if (conn == null) {
      try {
        if(dbproperties==null) {
          loadProperties();
        }
        Class.forName(dbproperties.getProperty("connection.driver_class"));
        conn = DriverManager.getConnection(
            dbproperties.getProperty("connection.url"),
            dbproperties.getProperty("connection.username"),
            dbproperties.getProperty("connection.password"));
        //自动提交事物属性为false
        conn.setAutoCommit(false);
        current.set(conn);
      }
      catch (SQLException ex) {
        throw new RuntimeException(ex.getMessage(),ex);
      }
      catch (ClassNotFoundException ex) {
        throw new RuntimeException(ex.getMessage(),ex);
      }
    }
    return conn;
  }

  /**
   * 关闭(释放)当前线程数据库连接
   */
  public static void closeConnection() {
//    try {
//      Connection conn = (Connection) current.get();
//      current.set(null);
//      if (conn != null) {
//        //清除缓存的Statement
//        StatementUtil.clearStatementCaches(conn);
//        conn.close();
//      }
//    }
//    catch (SQLException ex) {
//      log.fatal(ex.getMessage(),ex);
//    }
  }

  /**
   * 加载数据库连接配置属性
   */
  private static void loadProperties()  {
    dbproperties = new Properties();
    try {
      InputStream is = ConnectionUtil.class.getClassLoader()
          .getResourceAsStream("dbproperties.properties");
      dbproperties.load(is);
    }
    catch (IOException ex) {
      throw new RuntimeException(ex.getMessage(),ex);
    }
  }
}

⌨️ 快捷键说明

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