connectionutil.java

来自「办公自动化项目」· Java 代码 · 共 78 行

JAVA
78
字号
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 + =
减小字号Ctrl + -
显示快捷键?