为 JDBC 连接设置网络超时

为 JDBC 连接设置网络超时

问题描述:

我正在尝试使用 Java 设置我的 Oracle 数据库连接的网络超时.但是,我收到一个错误.以下是示例代码及其各自的例外情况.

I'm trying to set a network time-out my Oracle database Connection in Java. However, I'm getting an error. Below is sample code and it's respective exception.

try{
    conn = new Database("oracle").connect();
    conn.setNetworkTimeout(null, 30000); //I don't have an Executor, so the field is set to null
    System.out.println(Switch.date() + " -> Database Connection Initialized");
}
catch(SQLException ex){
    Logger.getLogger(Switch.class.getName()).log(Level.SEVERE, null, ex);
}

我得到的异常是:

Exception in thread "main" java.lang.AbstractMethodError:oracle.jdbc.driver.T4CConnection.setNetworkTimeout(Ljava/util/concurrent/Executor;I)V
   at ke.co.smart.Switch.<init>(Switch.java:524)
   at ke.co.smart.Switch.main(Switch.java:161)
Java Result: 1

我相信这与抽象方法有关(阅读 AbstractMethodError).什么可能导致这个错误,因为我只实现了我认为已经在 J​​ava 中定义的方法,因此不会拒绝编译.

I believe it has to do with a method being abstract (read AbstractMethodError). What could probably cause this error as I have only implemented the method which I think is already defined within Java, and thus, does not refuse to compile.

注意:如果有抽象方法,Java 不允许编译具体类.

setNetworkTimeout() 在 JDBC 4.1 中引入,在 JDBC 4.0 中不存在.

setNetworkTimeout() was introduced in JDBC 4.1 and was not present in JDBC 4.0.

如果您想使用 setNetworkTimeout() 方法,您将需要 ojdbc7,因为 JDBC 4.1 只随 Java 7 一起出现.

You will want ojdbc7 since JDBC 4.1 only came in with Java 7 if you want to use setNetworkTimeout() method.

潜在的问题是,在以后的规范中向接口添加方法可能会导致这些接口的旧实现因错误而中断.即将推出的 Java 8 的新特性之一,默认方法,有望让这个问题稍微减少一些.

The underlying issue is that adding methods to interfaces in later specifications can cause older implementations of those interfaces to break with errors. One of the new features of the upcoming Java 8, default methods, will hopefully make this slightly less of a problem.

显然 Oracle 还有一个 JDBC 驱动程序属性可以修改套接字超时.

Apparently there is also a JDBC driver property for Oracle that can modify socket timeouts.

您也可以尝试使用此 Oracle JDBC 属性 如果您使用的是瘦驱动程序,则设置套接字超时:

You can also try using this Oracle JDBC property to set the socket timeout if you are using the thin driver:

Properties props = new Properties();
props.setProperty("user", "dbuser");
props.setProperty("password", "dbpassword");
props.setProperty(OracleConnection.CONNECTION_PROPERTY_THIN_NET_CONNECT_TIMEOUT, "2000");

Connection con = DriverManager.getConnection("<JDBC connection string>", props);