I am getting null pointer exception in connection establishment - java

Here I am using jdbcHelper to establish connection with database but some times(not all the times) I am getting exception as null pointer in connection establishment but that is not all the time.
here is my code.This code is used to insert data into database..
Connection conn = JDBCHelper.getConnection();
PreparedStatement ps1 = null;
System.out.println("In Side DATA BASE");
System.out.println("in side database deviceid=" + s);
System.out.println("in side database rfide=" + s1);
System.out.println("in side database longitude=" + lati);
System.out.println("in side database latitude= " + lot);
System.out.println("in side database datalength=" + data_length);
Date date = new Date();
java.sql.Timestamp dt = new java.sql.Timestamp(date.getTime());
int flag = 1;
System.out.println("date=" + dt);
System.out.println("flag=" + flag);
try {
String hql = "insert into gpsData1(dateTime,deviceid,latitude,longitude,rfid,flag,datalength) values(?,?,?,?,?,?,?)";
ps1 = conn.prepareStatement(hql);
ps1.setString(1, dt.toString());
ps1.setString(2, s);
ps1.setFloat(3, lati);
ps1.setFloat(4, lot);
ps1.setString(5, s1);
ps1.setInt(6, flag);
ps1.setInt(7, data_length);
ps1.executeUpdate();
conn.commit();
System.out.println("DATA BASE Inserting Completed");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
JDBCHelper.close(ps1);
JDBCHelper.close(conn);
}
This is my JDBC code..
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCHelper {
public static final String url = "jdbc:mysql://localhost:3306/treamisdemo";
public static final String uid = "root";
public static final String pwd = "myserver";
/**
* #param
* args
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("connection is sucessful");
} catch (ClassNotFoundException e) {
System.err.println("ERROR: failed to load mysql JDBC driver.");
e.printStackTrace();
}
}
public static void close(ResultSet c) {
try {
if (c != null) {
c.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Statement c) {
try {
if (c != null) {
c.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Connection c) {
try {
if (c != null) {
c.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection(url, uid, pwd);
System.out.println("obtain connection =" + con);
con.setAutoCommit(false);
return con;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
This is the stack trace..
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data sourc
e rejected establishment of connection, message from server: "Too many connecti
ons"
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
orAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
onstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1128)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2336)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2
369)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2153)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.GeneratedConstructorAccessor39.newInstance(Unknown Source
)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
onstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java
:305)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.treamis.transport.vehicle.JDBCHelper.getConnection(JDBCHelper.jav
a:71)
at com.treamis.transport.vehicle.MyTimerTask.getRoutePointList(MyTimerTa
sk.java:639)
at com.treamis.transport.vehicle.MyTimerTask.sendSms(MyTimerTask.java:10
8)
at com.treamis.transport.vehicle.MyTimerTask.run(MyTimerTask.java:71)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)

The exception states: "Too many connections"
You must close every connection after you finished using it.
Sometimes you don't close the connection you open. You should move getConnection call inside the try block so you will always close if in finally statement.
Another possible reason is that you try to connect too many times simultaneously.
Suggestions:
The connection should be opened only when needed. No need to open it immediately at the beginning of the function.
The NPE you get is because getConnection() returns null on error. I think it is better to throw an exception in this case rather than return null.
If you use Java 7, you can use try-with-resources to close resources after finished using them.
Make sure you use reasonable amount of DB connections. If you need more than available connection, consider using one connection for all your DB accesses.

You can use a single connection for this Timer task. Commit on sucessful update but dont close the connection, reuse it.
Something like this:
boolean doInsert(){
// your insert code
// String hql = "insert into gpsData1(dateTime,deviceid,latitude,longitude,rfid
return ps1.executeUpdate(); // this returns true or false
}
boolean isInsert = doInsert();
if(isInsert){
conn.commit();
}

Use a real connection pool like HikariCP or BoneCP.

Related

How to get a String from a field

I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful

cannot exexute SQL query wirh OJDBC and Oracle DB (but full working with posgtres JDBC and Postgres DB)

I wrote a java program which retrieve data from a PG gb, process them, and write them in an Oracle DB.
While the PG part is fully working, the Oracle one has issues.
I can connect to the DB, but every query ends with a rollback (ResultSet with Oracle is always null)
Of course i have both PG and Oracle JDBC driver.
Here are my DBs object and testing queries
private final static PostgresDB postgres = new PostgresDB("jdbc:postgresql://192.168.2.23:5432/T18CLEAN", "myPGUser", "myPGPasswd", true);
private final static OracleDB oracle = new OracleDB("jdbc:oracle:thin:#192.168.2.20:1521/EFFEVI.T18FV.IT", "myOracleUser", "myOraclePasswd");
private final static String testPostgres = "SELECT product_pricelist_item.x_product_name FROM public.product_pricelist_item;";
private final static String testOracle = "SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Then I setup the 2 connections:
PG:
public Connection getConnect() throws ClassNotFoundException {
System.out.println("-------- Posgres JDBC Connection Testing ------");
String url = c_url;
Connection conn = null;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", passwd);
props.setProperty("ssl", boolToString(sslEnabled));
try{
Class.forName("org.postgresql.Driver");
System.out.println("Postgres JDBC Driver Registered!");
} catch(ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
try {
conn = DriverManager.getConnection(url, props);
System.out.println("You made it, take control your Postgres database now!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Failed to make connection to Postgres DB!");
}
return conn;
}
Oracle:
public Connection getConnect(){
Connection connection = null;
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return connection;
}
System.out.println("Oracle JDBC Driver Registered!");
try {
connection = DriverManager.getConnection(c_url, user, passwd);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return connection;
}
if (connection != null) {
System.out.println("You made it, take control your Oracle database now!");
return connection;
} else {
System.out.println("Failed to make connection to Oracle DB!");
}
return connection;
}
After all these pass i perform queries
public ResultSet executeCommand(Connection c, String command) {
Statement st = null;
ResultSet rs = null;
try {
st = c.createStatement();
rs = st.executeQuery(command);
} catch (SQLException e) {
}
if(rs==null){
System.out.println("Failed to Execute command " + command);
} else {
System.out.println("Command Executed: " + command);
}
return rs;
}
Assuming that there are no parameters error... What could it be? Any help?
Thank you very much
Remove a semicolon at the end of the query.
Use this:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI";
instead of this one:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Also don't silently "swallow" an exception in your code:
} catch (SQLException e) {
}
Rethrow the exception, or at least print the error to the log:
} catch (SQLException e) {
log.error("Error while executing query " + command, e);
throw new RuntimeException("Error while executing query " + command, e);
}

Connection from CachedRowSet

I have the following Java 7 code to create a CachedRowSet.
CachedRowSet crs = RowSetProvider.newFactory().createCachedRowSet();
Is there a way to get the Connection object from the CachedRowSet object? I would like to set autoCommit to false on the Connection object before invoking the acceptChanges() on CachedRowSet as I'm getting the following exception when invoking acceptChanges().
javax.sql.rowset.spi.SyncProviderException: Can't call commit when autocommit=true
There is a COMMIT_ON_ACCEPT_CHANGES field on CachedRowSet, but it's Deprecated.
Well, it took some time for me to reproduce the issue at my end. Setting the autoCommit value of the Connection to false via conn.setAutoCommit(false); resolved this issue.
Following is the sample working program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
public class CRSetChecker {
public static void main(String[] args) {
String connectString = "jdbc:oracle:thin:scott/tiger" +
"#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)" +
"(HOST=myorahost)(PORT=5521))" +
"(CONNECT_DATA=(SID=myorasid)))";
//Get DB connection
Connection conn = (new CRSet()).getConnection(connectString);
if (conn == null) {
System.out.println("Connection failed");
System.exit(0);
} else {
System.out.println("Connection established successfully!");
try {
CachedRowSet crs =
RowSetProvider.newFactory().createCachedRowSet();
String query="select ename from emp";
crs.setCommand(query);
crs.execute(conn);
//Set auto commit false
conn.setAutoCommit(false);
int count = 0;
while(crs.next()){
String name = crs.getString(1);
count++;
System.out.println(name);
if(count==1){
crs.updateString(1, "COOPER");
crs.updateRow();
crs.acceptChanges(conn);
System.out.println("After update:"+crs.getString(1));
}
}
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
public Connection getConnection(String connectString)
{
Connection con = null;
try {
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection(connectString);
} catch (SQLException ex) {
ex.printStackTrace();
}
return con;
}
}

Semi-Multi threaded JDBC connection

I have the following Callable instance where the SQLException is thrown here:
public long[] call() throws Exception {
long[] stats = new long[6];
try {
executer.acquire();
PreparedStatement statement =
connection
.prepareStatement("SELECT `War`.`EndTime` FROM `WarSim`.`War` WHERE `War`.`WarName` = ?");
statement.setString(1, warName);
ResultSet res = statement.executeQuery(); //<--------------SQLEXCEPTION HERE
if (res.first()) {
Timestamp ts = res.getTimestamp("EndTime");
if (ts != null)
stats[0] = 1;
statement =
connection
.prepareStatement("SELECT COUNT(`ID`) FROM `Missile` WHERE `WarName` = ?");
statement.setString(1, warName);
res = statement.executeQuery();
stats[1] = res.getInt(1);
statement =
connection
.prepareStatement("SELECT COUNT(`ID`) FROM `Missile` WHERE `WarName` = ? AND `Intercepted` = '1'");
statement.setString(1, warName);
res = statement.executeQuery();
stats[2] = res.getInt(1);
stats[3] = stats[1] - stats[2];
statement =
connection
.prepareStatement("SELECT COUNT(`ID`) FROM `EnemyLauncher` WHERE `WarName` = ? AND `Intercepted` = '1'");
statement.setString(1, warName);
res = statement.executeQuery();
stats[4] = res.getInt(1);
statement =
connection
.prepareStatement("SELECT SUM(`Damage`) FROM `Missile` WHERE `WarName` = ? AND `Intercepted` = '0'");
statement.setString(1, warName);
res = statement.executeQuery();
stats[5] = res.getInt(1);
}
} catch (SQLException e) {
System.out.println(warName + " is problematic");
while (e != null) {
System.out.println("\tmsg: " + e.getMessage()+
"\n\tstate: " + e.getSQLState());
e = e.getNextException();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
executer.release();
}
return stats;
}
executer is a single-permit, fair semaphore I use.
When I debug the code, everything works perfectly (no exceptions), yet when I run the program "normally" I get the "start of result set" SQLException thrown along with SQLState S1000.
How come I get exceptions even though I used a semaphore to acquire the mutex to query?
Help please :)
EDIT: here's the stack trace.
java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:929)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:841)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2672)
at db.jdbc.GetWarStatsTask.call(GetWarStatsTask.java:37)
at db.jdbc.GetWarStatsTask.call(GetWarStatsTask.java:1)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The class handling the Connection to the database:
public class JDBCConnection implements DBConnection {
private Connection connection;
private String dbUrl;
private Semaphore executer;
private ExecutorService es;
private static JDBCConnection instance;
public static JDBCConnection getInstance() {
if (instance == null) {
instance = new JDBCConnection();
}
return instance;
}
private JDBCConnection() {
dbUrl = "jdbc:mysql://---------/WarSim";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection =
DriverManager.getConnection(dbUrl, "------", "-------");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
while (e != null) {
System.out.println(e.getMessage());
e = e.getNextException();
}
}
es = Executors.newCachedThreadPool();
executer = new Semaphore(1, true);
}
public Future<long[]> getWarStats(String warName) {
return es.submit(new GetWarStatsTask(executer, connection, warName));
}
public void closeDB() {
try {
if (connection != null) {
connection.close();
}
} catch (Exception e) {
System.out.println("Could not close the current connection.");
e.printStackTrace();
}
}
Basically you are positioning the cursor before the first row and then requesting data. You need to move the cursor to the first row.
So first call result.next();
By the use of the semaphore, you understand the JDBC rule that a connection should only be in use by a single thread at a time. However, there are other threads that you need to be aware of, namely the garbage collector thread.
In this case, you need to close all the statement objects that are created before releasing the semaphore. If you don't close the statement objects, they will be closed by the garbage collector thread at an indeterminate time, causing unusual behavior on the connection.
So, before you prepare a new statement object, you need to close the old one.
statement.close()
statement =
connection
.prepareStatement("SELECT COUNT(ID) FROM Missile WHERE WarName = ?");
At the end you need to close the statement.
stats[5] = res.getInt(1);
statement.close()
You may want to get in the practice of running "findbugs" on your code. I think that may have spotted the problem of not closing the Statement object.

JDBC : Unable to connect second time

Hi All
I am trying to connect a data base. below i have given the code. I am able to connect to data base but unable to connect 2nd time if difference between 1st time and 2nd time is greater then "wait time out" of mysql data base.
I am using mysql data base. I am getting "Communications link failure" problem
wait_timeout is 10 sec (for convenience) it is 8 hour for my DB
I am giving you code
public class DatabaseManager {
private static Connection jConn;
private static DatabaseManager manager;
public Boolean getUser(){
Statement jStmt = null;
ResultSet rs = null;
try {
String query = "SELECT * FROM USER ";
System.out.println(query);
jStmt = jConn.createStatement();
rs = jStmt.executeQuery(query);
while (rs.next()) {
}
}catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public static synchronized DatabaseManager getInstance() {
if (manager == null) {
try {
manager = initialize();
} catch (DatabaseInitializationException e) {
// e.printStackTrace();
// throw new RuntimeException("Database Initialization
// Exception");
}
}
return manager;
}
private static DatabaseManager initialize()
throws DatabaseInitializationException {
try {
Class.forName(serverSrv.readPropertyValue("Srver_Path",
"DBdriver"));
} catch (ClassNotFoundException e) {
throw new DatabaseInitializationException(e.getMessage());
}
try {
jConn = DriverManager.getConnection("DB_URL","user","password");
System.out.println("Excecuted initialize() for Database ");
} catch (SQLException e) {
throw new DatabaseInitializationException(e.getMessage());
}
return new DatabaseManager();
}
}
AND I am testing like
public static void main(String[] args) {
long st = System.currentTimeMillis();
long end ;
DatabaseManager dm = DatabaseManager.getInstance();
if( dm.getUser() )
System.out.println("success");
else
System.out.println("failed..");
do{
end = System.currentTimeMillis();
}while( (end-st)<12*1000 );
if( dm.getUser() )
System.out.println("success");
else
System.out.println("failed..");
}
and it is giving exception like
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Last packet sent to the server was 0 ms ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2873)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2763)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3299)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1837)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1961)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2537)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2466)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1383)
at mypackage.db.DatabaseManager.getUser(DatabaseManager.java:127)
at mypackage.test.Test.main(Test.java:23)
Caused by: java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:113)
at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:160)
at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:188)
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2329)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2774)
Perhaps you should close the ResultSet as well as Statement.
This link has some tips on doing this correctly.
Your problem is that you are trying to reuse jConn which closes automatically after a timeout. So when you try and use it again an exception is thrown. Depending on what you are trying to do i would suggest (for simplicity) ..
Closing jConn by typeing jConn.close();
Then When you need to use the db again reconnect using jConn = DriverManager.getConnection("DB_URL","user","password");
Check your connection time out settings.

Categories