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

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. 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.(PhysicalConnection.java:439)

at oracle.jdbc.driver.T4CConnection.(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?

Edit:

If I set the DriverManager.setLoginTimeout(30); to 30 second, the exception happens so fast as before!

解决方案

Your 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.

To have no limit, set setLoginTimeout(0) where 0 means no limit.

I hope this helps.

Update if your instance xxx doesn't exists, how would you expect your Oracle Driver to connect to the database? It won't make any difference how long you set your loginTimeout there's not "host" to connect to.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值