19
Dec

Detecting connection leaks for your application

Following program can be used to create bulk connections to a database.  By default as soon as connection is closed there should be no connection leakage.

If your application makes DB connection (as per following program)

==============

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConnectionLeakDetector {

public static Connection getConnection() throws Exception {
Connection ret = null;
Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);
ret = DriverManager.getConnection(
“jdbc:sqlserver://192.168.152.1x;user=xx;password=xx;database=xx”);
try {
ret = new ro.kifs.diagnostic.Connection(ret);
} catch (Exception x) {
System.out.println(“EX registering conn in conn collection date: ” + x.getMessage());
x.printStackTrace();
}
return ret;
}

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
for (int k = 0; k < 2; k++) {

Connection conn = getConnection();
Statement sta = conn.createStatement();
String Sql = “select field1, field2 from table”;
ResultSet rs = sta.executeQuery(Sql);

while (rs.next()) {

String cStatusID = rs.getString(1);
String cStatus = rs.getString(2);

}
}
}

}

connections piled up at database level can be counted with following SQL Query:

 

SELECT DB_NAME(dbid) as DBName, COUNT(dbid) as NumberOfConnections, loginame as LoginName FROM sys.sysprocesses
WHERE dbid > 0 GROUP BY dbid, loginame

 

If number of connections do not drop after application is closed, we can assume a clear case of “Connection leakage” by application.