The following Java code sample isolates and demonstrates the problems we’re having with JDBC connections being closed when running against SQL Azure.
Basically the code performs one query, sleeps for 70 Seconds and then performs another query.
With an on premises SQL Server and other JDBC compliant databases, this works fine.
With SQL Azure, the connection gets closed during the sleep and we get:
com.microsoft.sqlserver.jdbc.SQLServerException: Connection reset by peer: socket write error
Contrary to the documentation, it seems that connections don't stay open beyond about 1 minute.
Any help or advice gratefully received.
/**
* JDBC against SQL Azure Problem Repro
*
* When run against SQL Azure, the second query fails with
* com.microsoft.sqlserver.jdbc.SQLServerException: Connection reset by peer: socket write error
*
* It works against on premises SQL Server
*
*/
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestAzureConnection {
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String username = "USER@SERVER";
String password = "PASSWORD";
Connection conn = DriverManager.getConnection("jdbc:sqlserver://SERVER.database.windows.net;DatabaseName=master", username, password);
//String username = "sa";
//String password = "password";
//Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost;DatabaseName=master", username, password);
System.out.println("First Query");
PreparedStatement pstmt = conn.prepareStatement("Select count(*) from sys.Tables");
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt(1));
}
long millis = 70000;
System.out.println("Sleeping for " + millis );
Thread.sleep(millis);
System.out.println("Second Query");
rs = pstmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt(1));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}