日期:2014-05-17  浏览次数:20741 次

请教:用单例模式封装了数据库连接的connection,需要关闭吗?
请教:用单例模式封装了数据库连接的connection,需要关闭吗?如果关闭会不会出问题,比如说:A线程拿到了连接connection,B线程同时也拿到了。A的事务完成后提交了,把connection关闭,B线程会不会出问题?
Java code


package com.gzsoft.secondWeb.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
 * 单例的模式
 * @author lyp
 *
 */
public class DB {
    
private static Connection conn=null;
private static String driver;
private static String connectionURL;
private static String username;
private static String password;

static{
    Properties p=new Properties();
    InputStream in=DB.class.getClassLoader().getResourceAsStream("connection.properties");
    try {
        p.load(in);
        driver=p.getProperty("driver");
        connectionURL=p.getProperty("connection_URL");
        username=p.getProperty("username");
        password=p.getProperty("password");
        
    } catch (IOException e) {
    }
    
}

public static Connection getConnetion(){
    if(conn==null){
        try {
            
            Class.forName(driver).newInstance();
            DriverManager.getConnection(connectionURL,username,password);
            System.out.print("success to connect to database!");
        } catch (InstantiationException e) {
           e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
           System.out.println("can't find the Driver");
        } catch (SQLException e) {
           System.out.println("fail to connect to database!");
        }
        
    }
    return conn;
    
}
public static void closeAll(ResultSet rs,PreparedStatement psmt,Connection conn){
    if(rs!=null){
        try {
            rs.close();
            rs=null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if(psmt!=null){
        try {
            psmt.close();
            psmt=null;
        } catch (SQLException e) {
           e.printStackTrace();
        }
    }
    if(conn!=null){
        try {
            conn.close();
            conn=null;
        } catch (SQLException e) {
           e.printStackTrace();
        }
    }
    
}
    
public static void main(String[] args) {
        System.out.println("driver:"+driver+"  connURL:"+connectionURL+"  username:"+username+"  password:"+password);
        getConnetion();
    }

}





------解决方案--------------------
探讨
多谢指教,我想知道是connection是不是实现了线程安全的啊?