WEB开发网
开发学院WEB开发Jsp 利用ThreadLocal简化struts开发 阅读

利用ThreadLocal简化struts开发

 2008-01-05 19:59:02 来源:WEB开发网   
核心提示:/* 获取connection 对象* /import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import Oracle.jdbc.driver.OracleDriver;/** * @author

/* 获取connection 对象* /
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import Oracle.jdbc.driver.OracleDriver;

/**
 * @author sfluo
 *
 * TODO To change the template for this generated type comment go to Window -
 * PReferences - Java - Code Style - Code Templates
 */
public class DBUtil {

 public static Connection conn;

 public static Connection getConnection() {

 try {

  DriverManager.registerDriver(new OracleDriver());
  conn = DriverManager.getConnection(
   "jdbc:oracle:thin:@10.100.143.161:1521:gb02", "gib", "gib");
 } catch (SQLException e) {
  e.printStackTrace();
 }

 return conn;
 }

}

利用ThreadLocal保存connection对象
package conn;

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

/**
 * @author sfluo
 *
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class ConnectionManage {
 private static ThreadLocal currentConn = new ThreadLocal();

 public static Connection currentConnection() {

 Connection conn = (Connection) currentConn.get();
 if (conn == null) {
  conn = DBUtil.getConnection();
  currentConn.set(conn);
  openTransaction();
 }
 return conn;
 }

 public static void closeConnection() {
 try {
  Connection conn = (Connection) currentConn.get();
  currentConn.set(null);
  if (conn != null) {
  conn.close();
  }
 } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

 }

 public static void openTransaction() {
 try {
  Connection conn = currentConnection();
  conn.setAutoCommit(false);
  conn.setTransactionIsolation(2);
 } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

 }

 public static void commit() {
 try {
  Connection conn = currentConnection();
  if (conn != null)
  conn.commit();
 } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }


Tags:利用 ThreadLocal 简化

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接