简体   繁体   English

在Java中设置Oracle 10g数据库连接超时

[英]Set Oracle 10g database connection timeout in Java

I tried to set a connection timeout with the following code: 我尝试使用以下代码设置连接超时:

public class ConnectionTimeout {  
  public static void main(String[] args) throws Exception {

    String entry = "jdbc:oracle:thin:@xxx:1521:xxx";
    Connection con=null;

    Class.forName("oracle.jdbc.driver.OracleDriver");

    DriverManager.setLoginTimeout(1);        
    con=DriverManager.getConnection(entry,"username","password");    

    Statement s=con.createStatement();    
    s.execute("select 1 from dual");    
    s.close();

    con.close();
  }
}

The instance xxx is not existing. 实例xxx不存在。 But I get the following exception: 但是我得到以下异常:

Exception in thread "main" java.sql.SQLException: E/A-Exception: Socket is not connected
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:255)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:439)
    at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at my.package.connection.timeout.ConnectionTimeout.main(ConnectionTimeout.java:22)

How I can implement a timeout to an not existing or available Oracle database instance? 如何对不存在或不可用的Oracle数据库实例实施超时?

Edit: If I set the DriverManager.setLoginTimeout(30); 编辑:如果我设置了DriverManager.setLoginTimeout(30); to 30 second, the exception happens so fast as before! 到30秒,异常发生的速度和以前一样快!

Your DriverManager.setLoginTimeout(1); 您的DriverManager.setLoginTimeout(1); sets the maximum time in seconds for the driver to wait while connecting to the database. 设置驱动程序在连接数据库时等待的最长时间(以单位) In your case, it's set to 1. 在您的情况下,它设置为1。

To have no limit, set setLoginTimeout(0) where 0 means no limit. 要没有限制,请设置setLoginTimeout(0) ,其中0表示没有限制。

I hope this helps. 我希望这有帮助。


Update if your instance xxx doesn't exists, how would you expect your Oracle Driver to connect to the database? 如果您的实例xxx不存在,请更新 ,您如何期望Oracle驱动程序连接到数据库? It won't make any difference how long you set your loginTimeout there's not "host" to connect to. 设置没有连接的“主机”的loginTimeout多长时间不会有任何区别。

Because, in Java doc, it shows: timeout in seconds, but in the implementation of JDBC Oracle, it is milliseconds. 因为在Java doc中,它显示:超时(以秒为单位),但是在JDBC Oracle的实现中,以毫秒为单位。

You can try using a measure of milliseconds. 您可以尝试使用毫秒为单位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM