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!");
}
}
}
Related
I have managed to pinpoint two of the mistakes I had and will therefore update my question.
Firstly, my previous error:
java.lang.ClassCastException: Bootstrap method returned null
was fixed by simply adding this line to build.graddle (app) dependencies:
implementation group: 'com.google.protobuf', name: 'protobuf-java', version: '3.6.0'
So that was nice, However this did not solve all my issues. This is my current register button method:
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
conn = Utils.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
});
As you can see I am focusing solely on getting a connection as it seems to be the heart of the problem. In debugging I also modified getConnection() to the following:
public static Connection getConnection() {
String driver = "com.mysql.cj.jdbc.Driver"; //com.mysql.jdbc.Driver doesn't work either
String url = "url";
String username = "user";
String password = "pass";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return null;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(url,username, password);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
return connection;
}
And this is the error that I am receiving now:
I/System.out: Connection Failed! Check output console
W/System.err: java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
W/System.err: Caused by: com.mysql.cj.exceptions.CJCommunicationsException: 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.
Caused by: java.net.SocketException: socket failed: EACCES (Permission denied)
I will keep this up to date on further changes. Again, if the issue is obvious I apologize in advance. Thanks for the help!
This question already has an answer here:
Caused by: java.lang.NoSuchMethodError: org.postgresql.core.BaseConnection.getEncoding()Lorg/postgresql/core/Encoding;
(1 answer)
Closed 4 years ago.
CODE:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aaa;
import static aaa.DB.geom;
import static aaa.DB.getConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
public static void main(String[] argv) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
// Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres", "postgres",
"abc");
} 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!");
//Connection conn = getConnection();
connection.setAutoCommit(false);
Statement s = null;
try {
s = connection.createStatement();
} catch (Exception e) {
System.out.println("statmnt connection not works");
}
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ss.executeUpdate();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
String query = "CREATE TABLE COMPANY(ID INT );";
ResultSet r = s.executeQuery(query);
connection.commit();
} else {
System.out.println("Failed to make connection!");
}
}
}
RUN:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
You made it, take control your database now!
Exception in thread "main" java.lang.NoSuchMethodError:
org.postgresql.core.BaseConnection.getPreferQueryMode()Lorg/postgresql/jdbc/PreferQueryMode;
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:151)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:132)
at aaa.JDBCExample.main(JDBCExample.java:69)
C:\Users\Dell\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
QUESTION:Give me steps to solve it since database is connected already! What is the core of the problem?
The problem is that if database postgresql connected then why not insert into database. The tables are also available and seen from netbeans. There needs to be a way to solve this run time exception issue when there is a query execution... So I needed step by step details to make it correct.
A SELECT statements has to be executed using executeQuery(). executeUpdate() is for DML statements like UPDATE, INSERT, or DELETE that don't normally return a ResultSet. Also, a DDL statement like CREATE TABLE can not be executed using executeQuery() you need execute() or executeUpdate() for that.
So your code should be:
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ResultSet rs = ss.executeQuery();
while (rs.next() {
// do something
}
rs.close();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
And:
String query = "CREATE TABLE COMPANY(ID INT );";
s.execute(query);
connection.commit();
You have connection.setAutoCommit(false); and you didnt commit after performing update. You have to commit your transaction in order for changes to apply. You can also setAutoCommit(true);
This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 4 years ago.
I have settled MAMP on my machine and last time when I used that code on my old computer and with another database that works pretty well. Now I cannot understand where I am wrong.
public class JDBC {
private static String DBURL = "jdbc:mysql://localhost:3306/BookReservationDatabase";
private static String DBLOGIN = "root";
private static String DBPASSWORD = "root";
public static void main(String[] args) {
// Step1: register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// Step 2: Establish the connection to the database
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
conn = DriverManager.getConnection(DBURL, DBLOGIN, DBPASSWORD);
// Step 3: Create statements (SQL queries)
stmt = conn.createStatement();
// Step 4: Execute statements and retrieve results
rset = stmt.executeQuery("SELECT * FROM Users");
// Step 5: Analyze results
while (rset.next()) {
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Step 6: Release resources
try {
if (rset != null)
rset.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (stmt != null)
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
My database name is BookReservationDatabase, I use root as a login and password on PhpMyAdmin.
I have got the following errors :
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: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:990)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:342)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2188)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2221)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2016)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:776)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
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.ConnectionImpl.getInstance(ConnectionImpl.java:386)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at features.JDBC.main(JDBC.java:26)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:301)
... 15 more
The error must be among DBURL,DBLOGIN and DBPASSWORD. Because the code generate error at the connection
conn = DriverManager.getConnection(DBURL, DBLOGIN, DBPASSWORD);
java.net.ConnectException: Connection refused (Connection refused)
clearly signals a communication error on the machine on which you run this code. This could be caused by many reasons, thus I merely list the most likely ones:
MySQL is not running at all.
Did you start it? Verify by inspecting running process lists (depends on OS).
MySQL is not listening on Port 3306 which is the default port.
Did you change it? If so, change your code/config accordingly.
In case a firewall is active, check the rules that could prevent connections on port 3306.
Hope it helps.
I am having issues connecting to mySQL server using ConnectJ driver for JDBC.
I wrote a simple program just to establish connectivity as below:
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://[host]:1521/OBIEE11G";
private static final String DB_USER = "OBADW";
private static final String DB_PASSWORD = "OBADW";
public static Connection getConnection() {
Connection dbConnection = null;
try {
// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
try {
// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
System.out.println("before get connection ***********");
System.out.println("Java version: " + System.getProperty("java.version"));
Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("JDBC driver: " + driver.getMajorVersion() + "." + driver.getMinorVersion());
dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
System.out.println("Connection: " + dbConnection.getClass().getName());
System.out.println("after get connection ***********");
return dbConnection;
} catch (SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return dbConnection;
}
public static void main(String[] args) {
Connection dbConnection = getConnection();
if (dbConnection != null) {
System.out.println("Connected");
} else {
System.out.println("Failed");
}
I am getting the following error:
before get connection ***********
Java version: 1.7.0
JDBC driver: 5.1
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:85)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:57)
at java.lang.reflect.Constructor.newInstance(Constructor.java:541)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:983)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:628)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1014)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2254)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2285)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2084)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:85)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:57)
at java.lang.reflect.Constructor.newInstance(Constructor.java:541)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:226)
at JDBCConnection.getConnection(JDBCConnection.java:32)
at JDBCConnection.main(JDBCConnection.java:45)
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2949)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:560)
... 17 more
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.
Failed
I am using connectJ : mysql-connector-java-5.1.37-bin.jar
Java 1.7, JDBC driver 5.1
I am able to ping the host, and connect it using mysql developer.
Please suggest.
From your log its clear about "Communications link failure"
ensure your mysql server running
ensure you have the right hostname/ip/port
ensure your network is working
Sounds stupid to ask but have you configured your MySQL Connector.jar file correctly in your project properties?
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.