Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在不终止JVM的情况下再次运行连接到数据库的java程序?_Java_Database_Database Connection_Connection Pooling - Fatal编程技术网

如何在不终止JVM的情况下再次运行连接到数据库的java程序?

如何在不终止JVM的情况下再次运行连接到数据库的java程序?,java,database,database-connection,connection-pooling,Java,Database,Database Connection,Connection Pooling,下面是我的连接池代码 public class ConnectionPoolManager { private static org.apache.log4j.Logger log; private String databaseUrl; String userName = null; String password = null; Properties prop = new Properties(); Vector connectionPool

下面是我的连接池代码

public class ConnectionPoolManager {

    private static org.apache.log4j.Logger log;
    private String databaseUrl;
    String userName = null;
    String password = null;
    Properties prop = new Properties();
    Vector connectionPool = new Vector();

    public ConnectionPoolManager() {

        databaseUrl();
        initialize();


    }

    public void databaseUrl() {

        try {
            URL url = getClass().getClassLoader().getResource("database.properties");

            // load a properties file
            prop.load(new FileInputStream(url.getPath()));
            // get the property value
            databaseUrl = prop.getProperty("database");
        } catch (IOException ex) {
            log.error("Date & Time: " + new Date() + ", Class Name : ConnectionPoolManager, Method Name : databaseUrl"
                    + "\n" + "Error : " + ex.getMessage());
        } catch (Exception e) {
            log.error("Date & Time: " + new Date() + ", Class Name : ConnectionPoolManager, Method Name : databaseUrl"
                    + "\n" + "Error : " + e.getMessage());
        }
        userName = prop.getProperty("username");
        password = prop.getProperty("password");

    }


    public ConnectionPoolManager(String databaseUrl, String userName, String password) {
        this.databaseUrl = databaseUrl;
        this.userName = userName;
        this.password = password;
        initialize();
    }

    private void initialize() {
        // Here we can initialize all the information that we need
        initializeConnectionPool();
    }

    private void initializeConnectionPool() {
        while (!checkIfConnectionPoolIsFull()) {
            System.out.println("Connection Pool is NOT full. Proceeding with adding new connections");
            // Adding new connection instance until the pool is full
            connectionPool.addElement(createNewConnectionForPool());
        }
        System.out.println("Connection Pool is full");
    }

    private synchronized boolean checkIfConnectionPoolIsFull() {
        final int MAX_POOL_SIZE = 5;

        // Check if the pool size
        if (connectionPool.size() < 5) {
            return false;
        }

        return true;
    }

    // Creating a connection
    private Connection createNewConnectionForPool() {
        Connection connection = null;

        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            // connection = DriverManager.getConnection(databaseUrl, userName,
            // password);
            connection = DriverManager.getConnection(databaseUrl);

        } catch (SQLException sqle) {
            System.err.println("SQLException: " + sqle);
            return null;
        } catch (ClassNotFoundException cnfe) {
            System.err.println("ClassNotFoundException: " + cnfe);
            return null;
        }

        return connection;
    }

    public synchronized Connection getConnectionFromPool() {

        Connection connection = null;

        // Check if there is a connection available. There are times when all
        // the connections in the pool may be used up
        if (connectionPool.size() > 0) {
            connection = (Connection) connectionPool.firstElement();
            connectionPool.removeElementAt(0);
        }
        // Giving away the connection from the connection pool
        return connection;
    }

    /**
     * The method adds the connection from the client back to the connection
     * pool
     * 
     * @return void
     * @param connection
     */
    public synchronized void returnConnectionToPool(Connection connection) {
        // Adding the connection from the client back to the connection pool
        connectionPool.addElement(connection);
    }

}
公共类连接池管理器{
私有静态org.apache.log4j.Logger日志;
私有字符串数据库URL;
字符串userName=null;
字符串密码=null;
Properties prop=新属性();
向量连接池=新向量();
公共连接池管理器(){
数据库URL();
初始化();
}
公共无效数据库URL(){
试一试{
URL URL=getClass().getClassLoader().getResource(“database.properties”);
//加载属性文件
load(新文件输入流(url.getPath());
//获取属性值
databaseUrl=prop.getProperty(“数据库”);
}捕获(IOEX异常){
log.error(“日期和时间:“+new Date()+”,类名:ConnectionPoolManager,方法名:databaseUrl”
+“\n”+”错误:“+ex.getMessage());
}捕获(例外e){
log.error(“日期和时间:“+new Date()+”,类名:ConnectionPoolManager,方法名:databaseUrl”
+“\n”+”错误:“+e.getMessage());
}
用户名=prop.getProperty(“用户名”);
password=prop.getProperty(“密码”);
}
公共连接池管理器(字符串数据库URL、字符串用户名、字符串密码){
this.databaseUrl=databaseUrl;
this.userName=用户名;
this.password=密码;
初始化();
}
私有void初始化(){
//在这里,我们可以初始化我们需要的所有信息
初始化连接池();
}
私有void initializeConnectionPool(){
而(!checkIfConnectionPoolIsFull()){
System.out.println(“连接池未满,继续添加新连接”);
//添加新连接实例,直到池已满
addElement(createNewConnectionForPool());
}
System.out.println(“连接池已满”);
}
专用同步布尔值checkIfConnectionPoolIsFull(){
最终整数最大池大小=5;
//检查池大小是否正确
if(connectionPool.size()<5){
返回false;
}
返回true;
}
//创建连接
专用连接createNewConnectionForPool(){
连接=空;
试一试{
Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);
//connection=DriverManager.getConnection(数据库URL、用户名、,
//密码);
connection=DriverManager.getConnection(数据库URL);
}捕获(SQLException sqle){
System.err.println(“SQLException:+sqle”);
返回null;
}捕获(ClassNotFoundException cnfe){
System.err.println(“ClassNotFoundException:+cnfe”);
返回null;
}
回路连接;
}
公共同步连接getConnectionFromPool(){
连接=空;
//检查是否有可用的连接。有时
//池中的连接可能已用完
如果(connectionPool.size()>0){
connection=(connection)connectionPool.firstElement();
connectionPool.removeElementAt(0);
}
//正在从连接池中放弃连接
回路连接;
}
/**
*该方法将客户端的连接添加回连接
*水池
* 
*@返回无效
*@param连接
*/
公共同步的void returnConnectionPool(连接){
//将连接从客户端添加回连接池
connectionPool.addElement(连接);
}
}
在我的实现类中,我使用finally块来关闭连接。 我不想调用
系统。从我的代码中退出(0)
。 我当前的代码第一次运行并将数据插入数据库,但没有终止JVM

当我下次尝试运行时,它会给出连接关闭异常,但我希望它插入到数据库中。
我怎样才能解决这个问题?

好吧,如果你关闭了一个连接,你就不能再使用它了。但是,保持它打开或创建一个新连接有什么问题?我不希望它一直处于打开状态,但是我应该在连接代码中做什么修改以再次建立连接?有没有方法创建两个不同的连接?当我第二次运行时,第一个连接将被终止,等等。这可以实现吗?好吧,您知道如何创建一个连接(
connection=DriverManager.getConnection(databaseUrl);
),那么创建另一个这样的连接有什么问题呢?请注意,连接池通常会保持连接打开,以减少开销。因此,当用户返回连接时,它可能根本不会关闭(除非池认为allready有太多连接,并决定删除一些连接)。如果代码被多次命中,我该怎么办?