我有Connection类的代码,它仅从一个数据库获取连接。看下面的DBConnection.java

package eksim.db.sql;

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


public class DBConnection {

    public Connection conn=null;
    private static DBConnection dbConn=null;
    static final String DB_URL=
            "jdbc:sqlserver://10.0.0.47\\test;databaseName=a;";
    static final String DB_USER="sa";
    static final String DB_PASS="123";




    public DBConnection(){
         if(conn==null){
             try{
                 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
                 conn=DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
             }
             catch(Exception ex){
                 ex.printStackTrace();
             }
         }
    }





    public static  DBConnection getInstance(){
        DBConnection conn=null;
        if(dbConn==null){
            System.out.println("New");
            dbConn=new DBConnection();
            conn=dbConn;
        } else{
            conn=dbConn;
        }
        return conn;
    }
    public Connection getCon() throws SQLException{
        return this.conn;
    }
}

现在,我想在另一个数据库中创建另一个连接。有人可以给我建议修改此代码,以便将Connection的结果输入2个数据库吗?感谢您的任何答复

最佳答案

public class DBConnection {

public Connection conn=null;
private static DBConnection dbConn=null;
static final String DB_URL=
        "jdbc:sqlserver://10.0.0.47\\test;databaseName=a;";
static final String DB_USER="sa";
static final String DB_PASS="123";


 public Connection secCon=null;
static final String DB_URL_SECOND= // URL

static final String DB_USER_SECOND=""; // user name
static final String DB_PASS_SECOND="123";




public DBConnection(){
     if(conn==null){
         try{
             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
             conn=DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
             secCon=DriverManager.getConnection(DB_URL_SECOND, DB_USER_SECOND, DB_PASS_SECOND);
         }
         catch(Exception ex){
             ex.printStackTrace();
         }
     }
}

08-04 10:22