JDBC : Unable to connect second time - java

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.

Related

Communications link failure when connecting to MySQL

I am fetching data from MySQL using JAVA JDBC driver.
Following exception is occurring:
"Communications link failure. The last packet successfully received
from the server was 14,380,298 milliseconds ago. The last packet sent
successfully to the server was 14,380,634 milliseconds ago.".
This error is occurring alternatively. That means if I run this for the first time no exception occur, but in the second time this exception occur. Then in the third run no exception give, in forth one again exception happen. I am using TimerTask to run the program every four hours.
Communication between the program and database works correctly when it run without exceptions.
Code is as follows:
public class CreatePO extends TimerTask {
public CreatePO() {
handler = new RFCHandler();
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("Run Create PO");
getItemFromDB();
sendDataToSap();
} catch (Exception e) {
e.printStackTrace();
}
}
private void getItemFromDB() {
// TODO Auto-generated method stub
System.out.println("Run get items from DB");
Connection connection = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
String queryOne = "SELECT reference_no, vendor_acc_no, date, mat_no,"
+ "po_qty, po_unit_measure, rate, order_price_unit, plant, user_name, email_id "
+ "FROM tbl_po_data WHERE status <> 'X'";
try {
pooler = DBPool_POSMS.getInstance();
dataSource1 = pooler.getDataSource();
System.out.println("PO pooler");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(" : PO pooler error");
}
try {
connection = dataSource1.getConnection();
connection.setAutoCommit(false);
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(queryOne);
int lineitem = 0;
rs.last();
rcount = rs.getRow();
rs.beforeFirst();
System.out.println("rcount = " + rcount);
System.out.println("PO while loop");
itemData = new Object[11][rcount];
if (rcount > 0) {
while (rs.next()) {
itemData[0][lineitem] = rs.getString("reference_no");
itemData[1][lineitem] = rs.getString("vendor_acc_no");
itemData[2][lineitem] = rs.getDate("date");
itemData[3][lineitem] = rs.getString("mat_no");
itemData[4][lineitem] = rs.getString("po_qty");
itemData[5][lineitem] = rs.getString("po_unit_measure");
itemData[6][lineitem] = rs.getString("rate");
itemData[7][lineitem] = rs.getString("order_price_unit");
itemData[8][lineitem] = rs.getString("plant");
itemData[9][lineitem] = rs.getString("user_name");
itemData[10][lineitem] = rs.getString("email_id");
lineitem = lineitem + 1;
}
rs.close();
st.close();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println(" : PO while loop error");
e1.printStackTrace();
} finally {
try {
connection.close();
System.out.println("Close connection one");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(" : Connection close error");
}
}
}
private void sendDataToSap() {
System.out.println("Send Data to Sap");
Table IT_LIST = null;
Table IT_RESPONSE = null;
try {
if (rcount > 0) {
}
}
} catch (Exception e) {
// TODO: handle exception
handler.releaseClient();
System.out.println(e + " : Handler release error");
}
finally {
rcount = 0;
}
}
Exception...
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 14,380,298 milliseconds ago. The last packet sent successfully to the server was 14,380,634 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:989)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3743)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2506)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2677)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
at com.mysql.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:4842)
at org.apache.commons.dbcp.DelegatingConnection.setAutoCommit(DelegatingConnection.java:371)
at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.setAutoCommit(PoolingDataSource.java:328)
at CreatePO.getItemFromDB(CreatePO.java:84)
at CreatePO.run(CreatePO.java:53)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Caused by: java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3725)
... 10 more
The problem is that your connection was open too long and was closed by MySQL server (as indicated by the "Connection reset by peer: socket write error" in the stacktrace). You need to configure your connection pool to either close too old connections, validate (test) the connection before handing it out or a combination of that.
You could also try increasing the timeout configuration in MySQL, but to be honest, a connection that was open for close to 4 hours (14 million milliseconds) may just need to be closed.

JSR 352: Connection is closed Error if connection is closed in the Readers close() in partitioned step

I create a Connection Connection con = ds.getConnection();(where ds is DataSource) in the open of the Reader and close it in the close() of the Reader.
But when i run a job with multiple partitions, in the middle of the job , i get Connection is closed error
Caused by: java.sql.SQLException: [jcc][t4][10335][10366][3.58.82] Invalid operation: Connection is closed. ERRORCODE=-4470, SQLSTATE=08003 DSRA0010E: SQL State = 08003, Error Code = -4,470
I assume this happens when one of the partition completes.
So my question is why does this happen? And how should connections be handled? Or does Java take care of closing the connections?
I am using Java Batch on WebSphere Liberty
UPDATE:
<jdbcDriver libraryRef="DB2JCC4Lib"/>
<properties.db2.jcc databaseName="" driverType="4" password="" portNumber="" queryDataSize="65535" serverName="" user=""/>
</dataSource>
public class Reader implements ItemReader {
private DataSource ds = null;
private Connection con = null;
public Reader() {
}
public void close() {
try {
con.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* #see ItemReader#readItem()
*/
public Object readItem() {
String s="";
try {
if (rs.next()) {
for (int i = 1; i <= 10; i++) {
s+=rs.getString(i);
}
return s;
}
else {
return null;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Serializable checkpointInfo() {
}
public void open(Serializable checkpoint) {
if (ds == null) {
try {
ds = (DataSource) new InitialContext()
.lookup("java:comp/env/jdbc/dataSource");
} catch (Exception e) {
e.printStackTrace();
}
}
try {
con = ds.getConnection();
statement= con
.prepareCall("call abc.xyz(?)");
statement.setString("param", "xxx");
boolean result= statement.execute();
if (result) {
rs = statement.getResultSet();
if (rs == null) {
throw new NullPointerException();
}
} else {
throw new SQLException();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Complete error message
[ERROR ] J2CA0024E: Method rollback, within transaction branch ID {XidImpl: formatId(57415344), gtrid_length(36), bqual_length(40),
data(0000015645eff4470000000915937ff85f46c3ed056b19010aa5147e1183f8d3ae81c04c0000015645eff4470000000915937ff85f46c3ed056b19010aa5147e1183f8d3ae81c04c00000001)} of resource pool connectionManager[Pool], caught com.ibm.ws.exception.WsException: DSRA0080E: An exception was received by the Data Store Adapter. See original exception message: [jcc][t4][10335][10366][3.58.82] Invalid operation: Connection is closed. ERRORCODE=-4470, SQLSTATE=08003. with SQL State : 08003 SQL Code : -4470
I dont't know if JSR-352's Batch handles processing exactly the same way as Spring Batch does but...
In Spring Batch if you have a Reader that uses chunk processing what i think you could do to solve the problem is to put the openConnection() in the beforeRead() and the closeConnection() in the afterRead().
To do that you should implement a Listener. Check these out so you get an idea of what i'm talking about.
Spring Annotation Type BeforeRead
Interface ItemReadListener

What's wrong with my code Data source rejected establishment of connection, message from server: "Too many connections"

I am getting this error from the database
Data source rejected establishment of connection, message from
server: "Too many connections"
I am closing my connections properly, I don't know why i am getting this error when my thread pool is only 5 and i think i am closing the connections. Anyone know why.
Below is my code. I have changed a few things to stay anonymous
public class myMain {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < (569743 / 100); i++) {
try {
MyClass mclass = new MyClass();
executor.execute(mclass);
} catch (Exception e) {
e.printStackTrace();
}
}
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finished all threads");
}
}
.
public class MyClass implements Runnable {
public MyClass(){
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/mytable?" + "user=&password=");
}
public void run() {
try {
String sql = "My select STATEMENT";
PreparedStatement stmt = connect.prepareStatement(sql);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
try {
int id = rs.getInt("movie_id");
String title = rs.getString("title");
int year = rs.getInt("year");
String trailerUrl = rs.getString("trailerUrl");
if (trailerUrl == null || (trailerUrl != null && trailerUrl.length() == 0)) {
YoutubeTrailerFetcher youtube = new YoutubeTrailerFetcher(title, year);
String trailer = youtube.getVideoId();
String updateSql = "my UPDATE Statement";
Statement updateStm = connect.createStatement();
updateStm.executeUpdate(updateSql);
updateStm.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
connect.close();
stmt.close();
rs.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
The main problem with your code is that you open a connection in the main thread, when calling the MyClass constructor, but the connection is only closed after the thread pool has finished executing the task. So you're trying to open 5697 connections, which is a whole lot. And these connections wait for being closed that one of the 5 threads in the pool has finished executing the task.
As I said in my comment: the method opening the connection should be the one closing it. And it should be closed in a finally block to ensure it is closed, whatever happens in the method, or better, you should use the try-with-resources statement to ensure that

How to remove this exception while making jdbc example ?

I am creating a simple example of jdbc .I am getting this error .I run my sql server on my mac machine .can you please tell me how to make connection with my sql and remove this error .I already include connector jar file .
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1129)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:358)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2489)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2311)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:347)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at HelloWorldExample.main(HelloWorldExample.java:17)
Caused by: java.net.UnknownHostException: local
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:877)
at java.net.InetAddress.getAddressFromNameService(InetAddress.java:1230)
at java.net.InetAddress.getAllByName0(InetAddress.java:1181)
at java.net.InetAddress.getAllByName(InetAddress.java:1111)
at java.net.InetAddress.getAllByName(InetAddress.java:1047)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:248)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:308)
... 15 more
Here is my code ..I am using mac
import java.sql.*;
/**
* HelloWorldExample : JDBC Tutorial that creates a simple database, stores in a single row
* and retrieves the data to then be displayed on standard out. The database is cleaned up
* to reduce clutter for this example.
* Author: Kevin Hooks
* Date: April 18th, 2012
**/
public class HelloWorldExample {
public static void main(String[] args) throws SQLException{
// Note that you can use TCP/IP by using this URL
// "jdbc:raima:rdm://localhost"
// The rdmsqlserver must be running to use TCP/IP
Connection Conn = DriverManager.getConnection("jdbc:mysql://local");
try {
Statement Stmt = Conn.createStatement();
try {
try { //Since the database is created here, it cannot be created twice
Stmt.execute("DROP DATABASE hello_db");
} catch (SQLException exception) {}
Stmt.execute("CREATE DATABASE hello_Db");
Stmt.execute("CREATE TABLE hello_table (f00 char(31))");
Conn.commit();
PreparedStatement PrepStmt = Conn.prepareStatement("INSERT INTO hello_table (f00) VALUES (?)");
try { //Sets parameter value to a string
PrepStmt.setString(1, "Hello World!");
PrepStmt.execute();
Conn.commit();
ResultSet RS = Stmt.executeQuery("SELECT * FROM hello_table");
try {
while(RS.next() != false) {
System.out.println(RS.getString(1));
}
} finally {
RS.close();
}
} finally { //Cleans up by dropping database in this case
Stmt.execute("DROP DATABASE hello_db");
PrepStmt.close();
}
} finally {
Stmt.close();
}
} catch (SQLException exception) {
System.err.println("SQLException: " + exception.toString());
}finally {
Conn.close();
}
}
}
The hostname of the loopback address is localhost, not local.
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at HelloWorldExample.main(HelloWorldExample.java:17)
Line 17:
Connection Conn = DriverManager.getConnection("jdbc:mysql://local");
Your program can not establish a connection to the database, be sure that you have your connection URL correct.
local, should be replaced by localhost, or 127.0.0.1
You should also note, that you never actually select a database to use.
you have declared wrong connection string. please modified it according to below rule
Connection Conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name");
your URL should be localhost then add the database name
have a look at this
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class JDBCExample {
public static void main(String[] argv) {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/mkyongcom","root", "password");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}

I am getting null pointer exception in connection establishment

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.

Categories