Reputation: 551
I am usingsqljdbc4.jar
for connection from my application to SQL Server via wifi. The connection works fine and queries too, but sometimes the wifi falls and I need to react - try to reconnect and then inform the user about a connection fail.
The issue is, even when I set query timeout, the execution hangs in case of disconnection and no SqlTimeoutException
is fired.
The connection (username and psw deleted):
SQLconnection = DriverManager.getConnection("jdbc:sqlserver://%address%;user=%UserName%;password=%password%;database=%db_name%");
SQLSelectStatement = SQLconnection.createStatement();
SQLSelectStatement.setQueryTimeout(2);
Execution of query:
String sql = "%my query%";
ResultSet rs;
try {
rs = SQLSelectStatement.executeQuery(sql);
} catch (SQLException sqle) {
ConnectSQL(); //try to connect again
rs = SQLSelectStatement.executeQuery(sql);
}
If the method throws a SQLException
, I'll inform the user and continue. But the exception is never thrown, even in the case of connection lost.
What can I do to resolve this? I tried setting lock-timeout and logintimeout in connection string based on MSDN, method SQLconnection.setNetworkTimeout
fires error too (if I understand it right, it is not implemented in microsoft driver).
The last solution I can think of is to implement some kind of timeout on my own, which will stop the query thread after a certain time. But I don't wont to reinvent the wheel.
Upvotes: 2
Views: 9838
Reputation: 9406
Additionally, recent Microsoft driver supports it as well: https://github.com/Microsoft/mssql-jdbc/pull/85/files
Upvotes: 2
Reputation: 551
Based on my googling and reading, setQueryTimeout
is useful only for limitting of query execution time, not for detecting of connection error.
I have found this great article describing timeouts in JDBC drivers. All I needed was to hit socketTimeout
which is not supported in MS JDBC driver.
I switched to jTDS driver and rewrited my code a bit. Now it works as I expected.
//initialize SQL connection
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Cls_log.LogError(ex);
}
private void ConnectSQL() {
try {
String url = "jdbc:jtds:sqlserver://<ip_address>/<db_name>;instance=<SQLserver_name>;loginTimeout=5;socketTimeout=2";
SQLconnection = DriverManager.getConnection(url, <userName>, <password>);
SQLSelectStatement = SQLconnection.createStatement();
} catch (SQLException ex) {
Cls_log.LogError(ex);
}
}
Executing my query
String sql = "%my query%";
ResultSet rs;
try {
rs = SQLSelectStatement.executeQuery(sql);
} catch (SQLException sqle) {
ConnectSQL(); //try to connect again
rs = SQLSelectStatement.executeQuery(sql);
}
If this throws SQLException, I inform user and offer workaround.
Upvotes: 6