可重新启动以访问数据库

时间:2012-03-07 15:06:37

标签: java oracle jdbc

我正在尝试访问oracle数据库,请参阅下面的代码。

问题是数据库是群集数据库,因此如果数据库已关闭,则可以访问另一个数据库。目前在一个节点上存在问题,因此我可以更新我的Java代码,如果失败则再次检查,直到建立连接为止?

我正在使用属性文件将凭据插入数据库。建立连接后,将输入查询并返回结果。

public static String connectDB(String configFile, String query) throws FileNotFoundException, IOException, SQLException, ClassNotFoundException{
    Properties p = new Properties();
    p.load(new FileInputStream(configFile));

    String serverName = (p.getProperty("RMS_DBServerName"));
    String portNumber = (p.getProperty("RMS_PortNumber"));
    String sid = (p.getProperty("RMS_SID"));
    String url = "jdbc:oracle:thin:@//" + serverName + ":" + portNumber + "/" + sid;
    String username = (p.getProperty("RMS_Username"));
    String password = (p.getProperty("RMS_Password"));

    Class.forName("oracle.jdbc.driver.OracleDriver");
    sleep(10);
    Connection connection = DriverManager.getConnection(url,username,password);
    sleep(5);
    String setr = null;
    try {      
        Statement stmt = connection.createStatement();
        try {
            ResultSet rset = stmt.executeQuery(query);
            try {
                    while(rset.next())   
                    setr = rset.getString(1);
                    return setr;  
            }        
            finally {
                try { 
                    rset.close(); 
                } 
                catch (Exception ignore) {}
            }
        } 
        finally {
            try { 
                stmt.close(); 
            } 
            catch (Exception ignore) {}
        }
    } 
    finally {
        try { 
            connection.close(); 
        } 
        catch (Exception ignore) {}
    }
}   

1 个答案:

答案 0 :(得分:0)

我不确定我理解你,但如果发生数据库访问错误,java.​sql.​DriverManager会抛出SQLException“。所以你基本上可以这样做:

public static String connectDB(String configFile, String query) 
    try{
      Connection connection = DriverManager.getConnection(url,username,password);
    } catch (SQLException ex) {
     sleep(10);
     connectDB(configFile,query); // try to connect again
    }

或者某事:

//dbPrefix is something that you put before name of every property associated to given node in your config file.
public static String connectDB(String configFile, String dbPrefix, String query) ... {
...
    String serverName = (p.getProperty(dbPrefix + "RMS_DBServerName"));
        String portNumber = (p.getProperty(dbPrefix + "RMS_PortNumber"));
        String sid = (p.getProperty(dbPrefix + "RMS_SID"));
        String url = "jdbc:oracle:thin:@//" + serverName + ":" + portNumber + "/" + sid;
        String username = (p.getProperty(dbPrefix + "RMS_Username"));
        String password = (p.getProperty(dbPrefix + "RMS_Password"));
...

        try{
          Connection connection = DriverManager.getConnection(url,username,password);
        } catch (SQLException ex) {
         sleep(10);
         connectDB(configFile,dbPrefix,query); // try to connect again, use different node
        }