Not able to execute Query in MariaDB using MySQL as Driver - java

I am testing one simple program that is connecting to DB and fetch my_test table details.
I am getting exception as java.sql.SQLException: Unable to load authentication plugin.
stack trace
java.sql.SQLException: Unable to load authentication plugin ''.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:923)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1715)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2412)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2445)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2230)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at TestRoot.main(TestRoot.java:19)
I am using Driver as MySQL.
My Database is mariadb-5.5.30.
Connection con=null;
Statement st=null;
ResultSet rs=null;
String firstName="";
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/my_test","root","");
st=con.createStatement() ;
rs=st.executeQuery("SELECT * FROM test") ;
while(rs.next())
{
firstName=rs.getString(2);
System.out.println(firstName);
}
}
catch(Exception err)
{
System.out.println(err.toString());
}
I knew Connection, ResultSet are not closed, but that cannot be the cause of issue I think.

You may want to take a look here : https://mariadb.atlassian.net/browse/MDEV-3935
the issue occurs when the password set on the mysql.user table uses an
older format - of the form 7f84554057dd964b (which I believe is
'badpwd') rather than something like
*AAB3E285149C0135D51A520E1940DD3263DC008C which is the newer form.
Resetting the password for the user record(s) as noted in MDEV-545
does solve the issue as it upgrades the password format in the tables.
From MariaDB documentation : https://mariadb.com/kb/en/pam-authentication-plugin/
Note: Windows does not use PAM, so the PAM authentication plugin does not work on Windows. However, one can use the Windows client to connect to a MariaDB server — on Linux or Solaris, for example — which does use the PAM authentication plugin. See this example.
From what I understand you should install it on linux (read the doc from the previous link)

I had the same problem and managed to fix it by changing the jdbc driver. I used MariaDB jdbc driver:
(from the Spring configuration file)
Hope this will be helpful.

Related

Communication link failure: JDBC [duplicate]

I'm working on getting my database to talk to my Java programs.
Can someone give me a quick and dirty sample program using the JDBC?
I'm getting a rather stupendous error:
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:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2260)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:787)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
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:409)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:357)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at SqlTest.main(SqlTest.java:22)
Caused by: 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:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2181)
... 12 more
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:218)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
... 13 more
Contents of the test file:
import com.mysql.jdbc.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlTest {
public static void main(String [] args) throws Exception {
// Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
// // edit the jdbc url
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/projects?user=user1&password=123");
// Statement st = conn.createStatement();
// ResultSet rs = st.executeQuery( "select * from table" );
System.out.println("Connected?");
}
}
So, you have a
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
java.net.ConnectException: Connection refused
I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
In my case, the solution was to add the expected TLS protocol to the connection string like this:
jdbc:mysql://localhost:3306/database_name?enabledTLSProtocols=TLSv1.2
For testing/development purposes (not recommended for production) you can also try:
jdbc:mysql://localhost:3306/database_name?useSSL=false&allowPublicKeyRetrieval=true
In my case, I needed to do a replacement of Localhost to the actual database server IP address
Instead of
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DBname", "root", "root");
I needed
Connection con = DriverManager.getConnection(
"jdbc:mysql://192.100.0.000:3306/DBname", "root", "root");
I catch this exception when Java out of heap. If I try to put in RAM many data items - first I catch "Communications link failure" and next "OutOfMemoryError".
I logged it and I decrease memory consumption (delete 1/2 data) and all ok.
This com.mysql.jdbc.exceptions.jdbc4.CommunicationsException exception occurs if your database connection is idle for long time.
This idle connection returns true on connection.isClosed(); but if we try to execute statement then it will fire this exception so I will suggest to go with database pooling.
In my case, turn out to be that the version of mysql-connector-java was too old.
In my demo, I somehow use mysql-connector-java like this:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
But in the develop environment, I use this:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
And my MySQL version was 5.1.48(yes, it is old, just for mimic the product version). So I met the same error.
Since the reason is found, the solution is found, too. Match the version!
I've been having the same problem for hours. I'm using MAMP Server
Instead of using localhost:[Apache Port], use your MySQL port.
Below is the default MySQL Port for MAMP server.
String url = "jdbc:mysql://localhost:8889/db_name";
Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);
Add this
useSSL=false&allowPublicKeyRetrieval=true
jdbc:mysql://localhost:3306/cloudapp?useSSL=false&allowPublicKeyRetrieval=true
https://youtu.be/ray3YvnIohM
This error may also happen if Java tries to connect to MySQL over SSL, but something goes wrong. (In my case, I was configuring Payara Server 5.193.1 connection pools to MySQL.)
Some people suggested setting useSSL=false. However, since Connector/J version 8.0.13, that setting is deprecated. Here's an excerpt from MySQL Connector/J 8.0 Configuration Properties:
sslMode
By default, network connections are SSL encrypted; this property permits secure connections to be turned off, or a different levels of security to be chosen. The following values are allowed: DISABLED - Establish unencrypted connections; PREFERRED - (default) Establish encrypted connections if the server enabled them, otherwise fall back to unencrypted connections; REQUIRED - Establish secure connections if the server enabled them, fail otherwise; VERIFY_CA - Like REQUIRED but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates; VERIFY_IDENTITY - Like VERIFY_CA, but additionally verify that the server certificate matches the host to which the connection is attempted.
This property replaced the deprecated legacy properties useSSL, requireSSL, and verifyServerCertificate, which are still accepted but translated into a value for sslMode if sslMode is not explicitly set: useSSL=false is translated to sslMode=DISABLED; {"useSSL=true", "requireSSL=false", "verifyServerCertificate=false"} is translated to sslMode=PREFERRED; {"useSSL=true", "requireSSL=true", "verifyServerCertificate=false"} is translated to sslMode=REQUIRED; {"useSSL=true" AND "verifyServerCertificate=true"} is translated to sslMode=VERIFY_CA. There is no equivalent legacy settings for sslMode=VERIFY_IDENTITY. Note that, for ALL server versions, the default setting of sslMode is PREFERRED, and it is equivalent to the legacy settings of useSSL=true, requireSSL=false, and verifyServerCertificate=false, which are different from their default settings for Connector/J 8.0.12 and earlier in some situations. Applications that continue to use the legacy properties and rely on their old default settings should be reviewed.
The legacy properties are ignored if sslMode is set explicitly. If none of sslMode or useSSL is set explicitly, the default setting of sslMode=PREFERRED applies.
Default: PREFERRED
Since version: 8.0.13
So, in my case, setting sslMode=DISABLED was all I needed to resolve the issue.
This was on a test machine. But for production, the secure solution would be properly configuring the Java client and MySQL server to use SSL.
Notice that by disabling SSL, you might also have to set allowPublicKeyRetrieval=true. (Again, not a wise decision from security standpoint). Further information is provided in MySQL ConnectionString Options:
AllowPublicKeyRetrieval
If the user account uses sha256_password authentication, the password must be protected during transmission; TLS is the preferred mechanism for this, but if it is not available then RSA public key encryption will be used. To specify the server’s RSA public key, use the ServerRSAPublicKeyFile connection string setting, or set AllowPublicKeyRetrieval=True to allow the client to automatically request the public key from the server. Note that AllowPublicKeyRetrieval=True could allow a malicious proxy to perform a MITM attack to get the plaintext password, so it is False by default and must be explicitly enabled.
I might be barking up the wrong tree here, but your exception seems to indicate your MySQL server isn't available.
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failureThe last packet sent successfully to the server was 0
milliseconds ago. The driver has not received any packets from the server. at...
What happens if you try (from the terminal)
mysql -u username -p
You will be prompted for the password associated with the username. After you give the correct password does the mysql client connect?
You may have to start MySQL from the Preferences if not. You can also set it to run at startup.
Earlier answers are appropriate . But , I would also like to point towards a more generic issue.
I faced similar issue and the reason was a network restriction of my company.
Same connection was getting successful when I was in any other network.
I got the same error because I was trying to run my program without starting mysql server.
After starting the mysql server, everything went right.
Please update your IP address in /etc/mysql/my.cnf file
bind-address = 0.0.0.0
Restart mysql deamon and mysql services.
Download MySQL-JDBC-Type-4-Treiber (i.g. 'mysql-connector-java-5.1.11-bin.jar' from 'mysql-connector-java-5.1.11.zip') at Mysql.
You need to inculde the driver jar during compile- and runtime in your classpath.
Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
// edit the jdbc url
Connection conn = DriverManager.getConnection( "jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName", username, password );
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery( "select * from table" );
My same problem is solved by the following steps:
Go to my.cnf
vi /etc/mysql/my.cnf
Modify its bind-address
"bind-address = 0.0.0.0"
Restart MySQL
sudo /etc/init.d/mysql restart
If you are using WAMP or XAMP server to install mysql database.
Then you have to explicitly start mysql sever other wise it will show
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure while connecting with database
i solved this problem in a easy way, that worked for me. i had the seme problem "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure". In my db.properties file i had this : url:jdbc:mysql://localhost:90/myDB,
only removed the port url , resulting in this manner url:jdbc:mysql://localhost/myDB and that worked for me.
Thats happened to me when I changed the mysql port from 3306 to 3307 in my.ini and the php.ini files but after changing the ports (3307->3306) back it worked fine again.
If you changed your port, you get this kind of error "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure"
Please check your port number
Try to change localhost to 127.0.0.1.
The localhost would be resolved to ::1. And MySQL cannot be connected via IPv6 by default.
And here is the output of telnet localhost 3306:
$ telnet localhost 3306
Trying ::1...
And there is no response from MySQL server.
Of course, please make sure your MySQL server is running.
dbhost=jdbc:mysql://172.18.23.100:3306/yourdatabase?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
user=root
password=Password#321
con = DriverManager.getConnection(dbhost, user, password);
if mysql version 8 or higher user updated connector
In my case, turn out to be that the version of mysql-connector-java was different.
I just changed mysql jdbc to maria jbdc
Old jdbc driver
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
New Jdbc driver
<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.6.2</version>
</dependency>
Just experienced this.
Got to make it work by:
(this can be placed in the static block intializer)
static{ // would have to be surrounded by try catch
Class.forName("com.mysql.jdbc.Driver"); // this will load the class Driver
}
Also by obtaining the connection through:
conn = DriverManager.getConnection(DBURL,<username>,<password>);
instead of specifying the login parameters
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/projects?user=user1&password=123");
Regards.
It could be a simple jar problem. may be you are using a old mysql-connector-java-XXX-bin.jar which is not supported by your current mysql version. i used mysql-connector-java-5.1.18-bin.jar as i am using mysql 5.5 and this problem is resolved for me.
My firewall was blocking post 3307 which my MySQL listening on. So I changed port from 3307 to 3306.Then I can successfully connect to a database.
I was receiving multiple errors such as:
CommunicationsException: Communications link failure
java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference at.
I had to add:
In AndroidManifest.xml include <uses-permission android:name="android.permission.INTERNET"/> just after the opening manifest tag.
Add the JDBC driver into your Gradle (or Maven) dependencies.
Sample jdbc connection class file. simply call the getConnection method when you want to get a connection. include related mysql-connector.jar
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public Connection getConnection() {
Connection con = null;
String dbhost;
String user;
String password;
// get properties
dbhost="jdbc:mysql://localhost:3306/cardmaildb";
user="root";
password="123";
System.out.println("S=======db Connecting======");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbhost, user, password);
//if you are facing with SSl issue please try this
//con = DriverManager.getConnection("jdbc:mysql://192.168.23.100:3306/cardmaildb?useUnicode=yes&characterEncoding=UTF-8&useSSL=false",user, password);
} catch (Exception e) {
System.err.println("error in connection");
e.printStackTrace();
}
System.out.println("E=======db Connecting======");
return con;
}
public static void main(String[] args) {
new DBConnection().getConnection();
}
}
For Remote Call to Mysql
Add remote user to Mysql from for exemple IP=remoteIP :
mysql -u xxxx -p //local coonection to mysql
mysql> GRANT ALL PRIVILEGES ON *.* TO 'theNewUser'#'remoteIP' IDENTIFIED BY 'passWord';
//Query OK, 0 rows affected (xx sec)
mysql> FLUSH PRIVILEGES;
//Query OK, 0 rows affected
Allow remote access to Mysql (by default all externall call is not allowed):
Edit
/etc/mysql/mysql.conf.d/mysqld.cnf or /etc/mysql/my.cnf
Change line: bind-address = 127.0.0.1 to
bind-address = 0.0.0.0
Restart Mysql: /etc/init.d/mysql restart
For The latest version of JDBC Driver, the JDBC :
jdbc.url='jdbc:mysql://remoteIP:3306/yourDbInstance?autoReconnect=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC'
jdbc.user='theNewUser'
Open file /etc/mysql/my.cnf:
change below parameter from
`bind-address = 127.0.0.1
to
bind-address = 0.0.0.0 #this allows all systems to connect
Run below command in mysql for specific IP Address->
grant all privileges on dbname.* to dbusername#'192.168.0.3' IDENTIFIED BY 'dbpassword';
If you want to give access to all IP Address, run below command:
grant all privileges on dbname.* to dbusername#'%' IDENTIFIED BY 'dbpassword';
I have the same connection error:
The problem I have is I used MySQL 8.0.15 but the Java Connector is 5.x.x.
Below is how I fixed it.
1. download the 8.0.15. from Maven repository:
https://search.maven.org/search?q=g:mysql%20AND%20a:mysql-connector-java
In the Eclipse IDE, select the "Referenced Libraries" in Explorer
Right Mouse Button > Build Path > Configure Build Path
a. remove the "mysql-connector-5.x.jar"
b. Click "Add External JARs..." and select mysql-connector-java-8.0.15.jar.
Re-run it, the problem went away.

What is the correct way to connect to an online database? [duplicate]

I'm working on getting my database to talk to my Java programs.
Can someone give me a quick and dirty sample program using the JDBC?
I'm getting a rather stupendous error:
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:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2260)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:787)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
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:409)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:357)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at SqlTest.main(SqlTest.java:22)
Caused by: 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:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2181)
... 12 more
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:218)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
... 13 more
Contents of the test file:
import com.mysql.jdbc.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlTest {
public static void main(String [] args) throws Exception {
// Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
// // edit the jdbc url
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/projects?user=user1&password=123");
// Statement st = conn.createStatement();
// ResultSet rs = st.executeQuery( "select * from table" );
System.out.println("Connected?");
}
}
So, you have a
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
java.net.ConnectException: Connection refused
I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
In my case, the solution was to add the expected TLS protocol to the connection string like this:
jdbc:mysql://localhost:3306/database_name?enabledTLSProtocols=TLSv1.2
For testing/development purposes (not recommended for production) you can also try:
jdbc:mysql://localhost:3306/database_name?useSSL=false&allowPublicKeyRetrieval=true
In my case, I needed to do a replacement of Localhost to the actual database server IP address
Instead of
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DBname", "root", "root");
I needed
Connection con = DriverManager.getConnection(
"jdbc:mysql://192.100.0.000:3306/DBname", "root", "root");
I catch this exception when Java out of heap. If I try to put in RAM many data items - first I catch "Communications link failure" and next "OutOfMemoryError".
I logged it and I decrease memory consumption (delete 1/2 data) and all ok.
This com.mysql.jdbc.exceptions.jdbc4.CommunicationsException exception occurs if your database connection is idle for long time.
This idle connection returns true on connection.isClosed(); but if we try to execute statement then it will fire this exception so I will suggest to go with database pooling.
In my case, turn out to be that the version of mysql-connector-java was too old.
In my demo, I somehow use mysql-connector-java like this:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
But in the develop environment, I use this:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
And my MySQL version was 5.1.48(yes, it is old, just for mimic the product version). So I met the same error.
Since the reason is found, the solution is found, too. Match the version!
I've been having the same problem for hours. I'm using MAMP Server
Instead of using localhost:[Apache Port], use your MySQL port.
Below is the default MySQL Port for MAMP server.
String url = "jdbc:mysql://localhost:8889/db_name";
Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);
Add this
useSSL=false&allowPublicKeyRetrieval=true
jdbc:mysql://localhost:3306/cloudapp?useSSL=false&allowPublicKeyRetrieval=true
https://youtu.be/ray3YvnIohM
This error may also happen if Java tries to connect to MySQL over SSL, but something goes wrong. (In my case, I was configuring Payara Server 5.193.1 connection pools to MySQL.)
Some people suggested setting useSSL=false. However, since Connector/J version 8.0.13, that setting is deprecated. Here's an excerpt from MySQL Connector/J 8.0 Configuration Properties:
sslMode
By default, network connections are SSL encrypted; this property permits secure connections to be turned off, or a different levels of security to be chosen. The following values are allowed: DISABLED - Establish unencrypted connections; PREFERRED - (default) Establish encrypted connections if the server enabled them, otherwise fall back to unencrypted connections; REQUIRED - Establish secure connections if the server enabled them, fail otherwise; VERIFY_CA - Like REQUIRED but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates; VERIFY_IDENTITY - Like VERIFY_CA, but additionally verify that the server certificate matches the host to which the connection is attempted.
This property replaced the deprecated legacy properties useSSL, requireSSL, and verifyServerCertificate, which are still accepted but translated into a value for sslMode if sslMode is not explicitly set: useSSL=false is translated to sslMode=DISABLED; {"useSSL=true", "requireSSL=false", "verifyServerCertificate=false"} is translated to sslMode=PREFERRED; {"useSSL=true", "requireSSL=true", "verifyServerCertificate=false"} is translated to sslMode=REQUIRED; {"useSSL=true" AND "verifyServerCertificate=true"} is translated to sslMode=VERIFY_CA. There is no equivalent legacy settings for sslMode=VERIFY_IDENTITY. Note that, for ALL server versions, the default setting of sslMode is PREFERRED, and it is equivalent to the legacy settings of useSSL=true, requireSSL=false, and verifyServerCertificate=false, which are different from their default settings for Connector/J 8.0.12 and earlier in some situations. Applications that continue to use the legacy properties and rely on their old default settings should be reviewed.
The legacy properties are ignored if sslMode is set explicitly. If none of sslMode or useSSL is set explicitly, the default setting of sslMode=PREFERRED applies.
Default: PREFERRED
Since version: 8.0.13
So, in my case, setting sslMode=DISABLED was all I needed to resolve the issue.
This was on a test machine. But for production, the secure solution would be properly configuring the Java client and MySQL server to use SSL.
Notice that by disabling SSL, you might also have to set allowPublicKeyRetrieval=true. (Again, not a wise decision from security standpoint). Further information is provided in MySQL ConnectionString Options:
AllowPublicKeyRetrieval
If the user account uses sha256_password authentication, the password must be protected during transmission; TLS is the preferred mechanism for this, but if it is not available then RSA public key encryption will be used. To specify the server’s RSA public key, use the ServerRSAPublicKeyFile connection string setting, or set AllowPublicKeyRetrieval=True to allow the client to automatically request the public key from the server. Note that AllowPublicKeyRetrieval=True could allow a malicious proxy to perform a MITM attack to get the plaintext password, so it is False by default and must be explicitly enabled.
I might be barking up the wrong tree here, but your exception seems to indicate your MySQL server isn't available.
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failureThe last packet sent successfully to the server was 0
milliseconds ago. The driver has not received any packets from the server. at...
What happens if you try (from the terminal)
mysql -u username -p
You will be prompted for the password associated with the username. After you give the correct password does the mysql client connect?
You may have to start MySQL from the Preferences if not. You can also set it to run at startup.
Earlier answers are appropriate . But , I would also like to point towards a more generic issue.
I faced similar issue and the reason was a network restriction of my company.
Same connection was getting successful when I was in any other network.
I got the same error because I was trying to run my program without starting mysql server.
After starting the mysql server, everything went right.
Please update your IP address in /etc/mysql/my.cnf file
bind-address = 0.0.0.0
Restart mysql deamon and mysql services.
Download MySQL-JDBC-Type-4-Treiber (i.g. 'mysql-connector-java-5.1.11-bin.jar' from 'mysql-connector-java-5.1.11.zip') at Mysql.
You need to inculde the driver jar during compile- and runtime in your classpath.
Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
// edit the jdbc url
Connection conn = DriverManager.getConnection( "jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName", username, password );
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery( "select * from table" );
My same problem is solved by the following steps:
Go to my.cnf
vi /etc/mysql/my.cnf
Modify its bind-address
"bind-address = 0.0.0.0"
Restart MySQL
sudo /etc/init.d/mysql restart
If you are using WAMP or XAMP server to install mysql database.
Then you have to explicitly start mysql sever other wise it will show
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure while connecting with database
i solved this problem in a easy way, that worked for me. i had the seme problem "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure". In my db.properties file i had this : url:jdbc:mysql://localhost:90/myDB,
only removed the port url , resulting in this manner url:jdbc:mysql://localhost/myDB and that worked for me.
Thats happened to me when I changed the mysql port from 3306 to 3307 in my.ini and the php.ini files but after changing the ports (3307->3306) back it worked fine again.
If you changed your port, you get this kind of error "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure"
Please check your port number
Try to change localhost to 127.0.0.1.
The localhost would be resolved to ::1. And MySQL cannot be connected via IPv6 by default.
And here is the output of telnet localhost 3306:
$ telnet localhost 3306
Trying ::1...
And there is no response from MySQL server.
Of course, please make sure your MySQL server is running.
dbhost=jdbc:mysql://172.18.23.100:3306/yourdatabase?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
user=root
password=Password#321
con = DriverManager.getConnection(dbhost, user, password);
if mysql version 8 or higher user updated connector
In my case, turn out to be that the version of mysql-connector-java was different.
I just changed mysql jdbc to maria jbdc
Old jdbc driver
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
New Jdbc driver
<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.6.2</version>
</dependency>
Just experienced this.
Got to make it work by:
(this can be placed in the static block intializer)
static{ // would have to be surrounded by try catch
Class.forName("com.mysql.jdbc.Driver"); // this will load the class Driver
}
Also by obtaining the connection through:
conn = DriverManager.getConnection(DBURL,<username>,<password>);
instead of specifying the login parameters
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/projects?user=user1&password=123");
Regards.
It could be a simple jar problem. may be you are using a old mysql-connector-java-XXX-bin.jar which is not supported by your current mysql version. i used mysql-connector-java-5.1.18-bin.jar as i am using mysql 5.5 and this problem is resolved for me.
My firewall was blocking post 3307 which my MySQL listening on. So I changed port from 3307 to 3306.Then I can successfully connect to a database.
I was receiving multiple errors such as:
CommunicationsException: Communications link failure
java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference at.
I had to add:
In AndroidManifest.xml include <uses-permission android:name="android.permission.INTERNET"/> just after the opening manifest tag.
Add the JDBC driver into your Gradle (or Maven) dependencies.
Sample jdbc connection class file. simply call the getConnection method when you want to get a connection. include related mysql-connector.jar
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public Connection getConnection() {
Connection con = null;
String dbhost;
String user;
String password;
// get properties
dbhost="jdbc:mysql://localhost:3306/cardmaildb";
user="root";
password="123";
System.out.println("S=======db Connecting======");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbhost, user, password);
//if you are facing with SSl issue please try this
//con = DriverManager.getConnection("jdbc:mysql://192.168.23.100:3306/cardmaildb?useUnicode=yes&characterEncoding=UTF-8&useSSL=false",user, password);
} catch (Exception e) {
System.err.println("error in connection");
e.printStackTrace();
}
System.out.println("E=======db Connecting======");
return con;
}
public static void main(String[] args) {
new DBConnection().getConnection();
}
}
For Remote Call to Mysql
Add remote user to Mysql from for exemple IP=remoteIP :
mysql -u xxxx -p //local coonection to mysql
mysql> GRANT ALL PRIVILEGES ON *.* TO 'theNewUser'#'remoteIP' IDENTIFIED BY 'passWord';
//Query OK, 0 rows affected (xx sec)
mysql> FLUSH PRIVILEGES;
//Query OK, 0 rows affected
Allow remote access to Mysql (by default all externall call is not allowed):
Edit
/etc/mysql/mysql.conf.d/mysqld.cnf or /etc/mysql/my.cnf
Change line: bind-address = 127.0.0.1 to
bind-address = 0.0.0.0
Restart Mysql: /etc/init.d/mysql restart
For The latest version of JDBC Driver, the JDBC :
jdbc.url='jdbc:mysql://remoteIP:3306/yourDbInstance?autoReconnect=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC'
jdbc.user='theNewUser'
Open file /etc/mysql/my.cnf:
change below parameter from
`bind-address = 127.0.0.1
to
bind-address = 0.0.0.0 #this allows all systems to connect
Run below command in mysql for specific IP Address->
grant all privileges on dbname.* to dbusername#'192.168.0.3' IDENTIFIED BY 'dbpassword';
If you want to give access to all IP Address, run below command:
grant all privileges on dbname.* to dbusername#'%' IDENTIFIED BY 'dbpassword';
I have the same connection error:
The problem I have is I used MySQL 8.0.15 but the Java Connector is 5.x.x.
Below is how I fixed it.
1. download the 8.0.15. from Maven repository:
https://search.maven.org/search?q=g:mysql%20AND%20a:mysql-connector-java
In the Eclipse IDE, select the "Referenced Libraries" in Explorer
Right Mouse Button > Build Path > Configure Build Path
a. remove the "mysql-connector-5.x.jar"
b. Click "Add External JARs..." and select mysql-connector-java-8.0.15.jar.
Re-run it, the problem went away.

Connect to online mysql database using java [duplicate]

I'm working on getting my database to talk to my Java programs.
Can someone give me a quick and dirty sample program using the JDBC?
I'm getting a rather stupendous error:
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:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2260)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:787)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
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:409)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:357)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at SqlTest.main(SqlTest.java:22)
Caused by: 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:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2181)
... 12 more
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:218)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
... 13 more
Contents of the test file:
import com.mysql.jdbc.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlTest {
public static void main(String [] args) throws Exception {
// Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
// // edit the jdbc url
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/projects?user=user1&password=123");
// Statement st = conn.createStatement();
// ResultSet rs = st.executeQuery( "select * from table" );
System.out.println("Connected?");
}
}
So, you have a
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
java.net.ConnectException: Connection refused
I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
In my case, the solution was to add the expected TLS protocol to the connection string like this:
jdbc:mysql://localhost:3306/database_name?enabledTLSProtocols=TLSv1.2
For testing/development purposes (not recommended for production) you can also try:
jdbc:mysql://localhost:3306/database_name?useSSL=false&allowPublicKeyRetrieval=true
In my case, I needed to do a replacement of Localhost to the actual database server IP address
Instead of
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DBname", "root", "root");
I needed
Connection con = DriverManager.getConnection(
"jdbc:mysql://192.100.0.000:3306/DBname", "root", "root");
I catch this exception when Java out of heap. If I try to put in RAM many data items - first I catch "Communications link failure" and next "OutOfMemoryError".
I logged it and I decrease memory consumption (delete 1/2 data) and all ok.
This com.mysql.jdbc.exceptions.jdbc4.CommunicationsException exception occurs if your database connection is idle for long time.
This idle connection returns true on connection.isClosed(); but if we try to execute statement then it will fire this exception so I will suggest to go with database pooling.
In my case, turn out to be that the version of mysql-connector-java was too old.
In my demo, I somehow use mysql-connector-java like this:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
But in the develop environment, I use this:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
And my MySQL version was 5.1.48(yes, it is old, just for mimic the product version). So I met the same error.
Since the reason is found, the solution is found, too. Match the version!
I've been having the same problem for hours. I'm using MAMP Server
Instead of using localhost:[Apache Port], use your MySQL port.
Below is the default MySQL Port for MAMP server.
String url = "jdbc:mysql://localhost:8889/db_name";
Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);
Add this
useSSL=false&allowPublicKeyRetrieval=true
jdbc:mysql://localhost:3306/cloudapp?useSSL=false&allowPublicKeyRetrieval=true
https://youtu.be/ray3YvnIohM
This error may also happen if Java tries to connect to MySQL over SSL, but something goes wrong. (In my case, I was configuring Payara Server 5.193.1 connection pools to MySQL.)
Some people suggested setting useSSL=false. However, since Connector/J version 8.0.13, that setting is deprecated. Here's an excerpt from MySQL Connector/J 8.0 Configuration Properties:
sslMode
By default, network connections are SSL encrypted; this property permits secure connections to be turned off, or a different levels of security to be chosen. The following values are allowed: DISABLED - Establish unencrypted connections; PREFERRED - (default) Establish encrypted connections if the server enabled them, otherwise fall back to unencrypted connections; REQUIRED - Establish secure connections if the server enabled them, fail otherwise; VERIFY_CA - Like REQUIRED but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates; VERIFY_IDENTITY - Like VERIFY_CA, but additionally verify that the server certificate matches the host to which the connection is attempted.
This property replaced the deprecated legacy properties useSSL, requireSSL, and verifyServerCertificate, which are still accepted but translated into a value for sslMode if sslMode is not explicitly set: useSSL=false is translated to sslMode=DISABLED; {"useSSL=true", "requireSSL=false", "verifyServerCertificate=false"} is translated to sslMode=PREFERRED; {"useSSL=true", "requireSSL=true", "verifyServerCertificate=false"} is translated to sslMode=REQUIRED; {"useSSL=true" AND "verifyServerCertificate=true"} is translated to sslMode=VERIFY_CA. There is no equivalent legacy settings for sslMode=VERIFY_IDENTITY. Note that, for ALL server versions, the default setting of sslMode is PREFERRED, and it is equivalent to the legacy settings of useSSL=true, requireSSL=false, and verifyServerCertificate=false, which are different from their default settings for Connector/J 8.0.12 and earlier in some situations. Applications that continue to use the legacy properties and rely on their old default settings should be reviewed.
The legacy properties are ignored if sslMode is set explicitly. If none of sslMode or useSSL is set explicitly, the default setting of sslMode=PREFERRED applies.
Default: PREFERRED
Since version: 8.0.13
So, in my case, setting sslMode=DISABLED was all I needed to resolve the issue.
This was on a test machine. But for production, the secure solution would be properly configuring the Java client and MySQL server to use SSL.
Notice that by disabling SSL, you might also have to set allowPublicKeyRetrieval=true. (Again, not a wise decision from security standpoint). Further information is provided in MySQL ConnectionString Options:
AllowPublicKeyRetrieval
If the user account uses sha256_password authentication, the password must be protected during transmission; TLS is the preferred mechanism for this, but if it is not available then RSA public key encryption will be used. To specify the server’s RSA public key, use the ServerRSAPublicKeyFile connection string setting, or set AllowPublicKeyRetrieval=True to allow the client to automatically request the public key from the server. Note that AllowPublicKeyRetrieval=True could allow a malicious proxy to perform a MITM attack to get the plaintext password, so it is False by default and must be explicitly enabled.
I might be barking up the wrong tree here, but your exception seems to indicate your MySQL server isn't available.
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failureThe last packet sent successfully to the server was 0
milliseconds ago. The driver has not received any packets from the server. at...
What happens if you try (from the terminal)
mysql -u username -p
You will be prompted for the password associated with the username. After you give the correct password does the mysql client connect?
You may have to start MySQL from the Preferences if not. You can also set it to run at startup.
Earlier answers are appropriate . But , I would also like to point towards a more generic issue.
I faced similar issue and the reason was a network restriction of my company.
Same connection was getting successful when I was in any other network.
I got the same error because I was trying to run my program without starting mysql server.
After starting the mysql server, everything went right.
Please update your IP address in /etc/mysql/my.cnf file
bind-address = 0.0.0.0
Restart mysql deamon and mysql services.
Download MySQL-JDBC-Type-4-Treiber (i.g. 'mysql-connector-java-5.1.11-bin.jar' from 'mysql-connector-java-5.1.11.zip') at Mysql.
You need to inculde the driver jar during compile- and runtime in your classpath.
Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
// edit the jdbc url
Connection conn = DriverManager.getConnection( "jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName", username, password );
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery( "select * from table" );
My same problem is solved by the following steps:
Go to my.cnf
vi /etc/mysql/my.cnf
Modify its bind-address
"bind-address = 0.0.0.0"
Restart MySQL
sudo /etc/init.d/mysql restart
If you are using WAMP or XAMP server to install mysql database.
Then you have to explicitly start mysql sever other wise it will show
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure while connecting with database
i solved this problem in a easy way, that worked for me. i had the seme problem "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure". In my db.properties file i had this : url:jdbc:mysql://localhost:90/myDB,
only removed the port url , resulting in this manner url:jdbc:mysql://localhost/myDB and that worked for me.
Thats happened to me when I changed the mysql port from 3306 to 3307 in my.ini and the php.ini files but after changing the ports (3307->3306) back it worked fine again.
If you changed your port, you get this kind of error "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure"
Please check your port number
Try to change localhost to 127.0.0.1.
The localhost would be resolved to ::1. And MySQL cannot be connected via IPv6 by default.
And here is the output of telnet localhost 3306:
$ telnet localhost 3306
Trying ::1...
And there is no response from MySQL server.
Of course, please make sure your MySQL server is running.
dbhost=jdbc:mysql://172.18.23.100:3306/yourdatabase?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
user=root
password=Password#321
con = DriverManager.getConnection(dbhost, user, password);
if mysql version 8 or higher user updated connector
In my case, turn out to be that the version of mysql-connector-java was different.
I just changed mysql jdbc to maria jbdc
Old jdbc driver
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
New Jdbc driver
<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.6.2</version>
</dependency>
Just experienced this.
Got to make it work by:
(this can be placed in the static block intializer)
static{ // would have to be surrounded by try catch
Class.forName("com.mysql.jdbc.Driver"); // this will load the class Driver
}
Also by obtaining the connection through:
conn = DriverManager.getConnection(DBURL,<username>,<password>);
instead of specifying the login parameters
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/projects?user=user1&password=123");
Regards.
It could be a simple jar problem. may be you are using a old mysql-connector-java-XXX-bin.jar which is not supported by your current mysql version. i used mysql-connector-java-5.1.18-bin.jar as i am using mysql 5.5 and this problem is resolved for me.
My firewall was blocking post 3307 which my MySQL listening on. So I changed port from 3307 to 3306.Then I can successfully connect to a database.
I was receiving multiple errors such as:
CommunicationsException: Communications link failure
java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference at.
I had to add:
In AndroidManifest.xml include <uses-permission android:name="android.permission.INTERNET"/> just after the opening manifest tag.
Add the JDBC driver into your Gradle (or Maven) dependencies.
Sample jdbc connection class file. simply call the getConnection method when you want to get a connection. include related mysql-connector.jar
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public Connection getConnection() {
Connection con = null;
String dbhost;
String user;
String password;
// get properties
dbhost="jdbc:mysql://localhost:3306/cardmaildb";
user="root";
password="123";
System.out.println("S=======db Connecting======");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbhost, user, password);
//if you are facing with SSl issue please try this
//con = DriverManager.getConnection("jdbc:mysql://192.168.23.100:3306/cardmaildb?useUnicode=yes&characterEncoding=UTF-8&useSSL=false",user, password);
} catch (Exception e) {
System.err.println("error in connection");
e.printStackTrace();
}
System.out.println("E=======db Connecting======");
return con;
}
public static void main(String[] args) {
new DBConnection().getConnection();
}
}
For Remote Call to Mysql
Add remote user to Mysql from for exemple IP=remoteIP :
mysql -u xxxx -p //local coonection to mysql
mysql> GRANT ALL PRIVILEGES ON *.* TO 'theNewUser'#'remoteIP' IDENTIFIED BY 'passWord';
//Query OK, 0 rows affected (xx sec)
mysql> FLUSH PRIVILEGES;
//Query OK, 0 rows affected
Allow remote access to Mysql (by default all externall call is not allowed):
Edit
/etc/mysql/mysql.conf.d/mysqld.cnf or /etc/mysql/my.cnf
Change line: bind-address = 127.0.0.1 to
bind-address = 0.0.0.0
Restart Mysql: /etc/init.d/mysql restart
For The latest version of JDBC Driver, the JDBC :
jdbc.url='jdbc:mysql://remoteIP:3306/yourDbInstance?autoReconnect=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC'
jdbc.user='theNewUser'
Open file /etc/mysql/my.cnf:
change below parameter from
`bind-address = 127.0.0.1
to
bind-address = 0.0.0.0 #this allows all systems to connect
Run below command in mysql for specific IP Address->
grant all privileges on dbname.* to dbusername#'192.168.0.3' IDENTIFIED BY 'dbpassword';
If you want to give access to all IP Address, run below command:
grant all privileges on dbname.* to dbusername#'%' IDENTIFIED BY 'dbpassword';
I have the same connection error:
The problem I have is I used MySQL 8.0.15 but the Java Connector is 5.x.x.
Below is how I fixed it.
1. download the 8.0.15. from Maven repository:
https://search.maven.org/search?q=g:mysql%20AND%20a:mysql-connector-java
In the Eclipse IDE, select the "Referenced Libraries" in Explorer
Right Mouse Button > Build Path > Configure Build Path
a. remove the "mysql-connector-5.x.jar"
b. Click "Add External JARs..." and select mysql-connector-java-8.0.15.jar.
Re-run it, the problem went away.

Error with sql and eclipse com.mysql.jdbc.exceptions.jdbc4.CommunicationsException [duplicate]

I'm working on getting my database to talk to my Java programs.
Can someone give me a quick and dirty sample program using the JDBC?
I'm getting a rather stupendous error:
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:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2260)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:787)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
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:409)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:357)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at SqlTest.main(SqlTest.java:22)
Caused by: 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:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2181)
... 12 more
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:218)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
... 13 more
Contents of the test file:
import com.mysql.jdbc.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlTest {
public static void main(String [] args) throws Exception {
// Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
// // edit the jdbc url
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/projects?user=user1&password=123");
// Statement st = conn.createStatement();
// ResultSet rs = st.executeQuery( "select * from table" );
System.out.println("Connected?");
}
}
So, you have a
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
java.net.ConnectException: Connection refused
I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
In my case, the solution was to add the expected TLS protocol to the connection string like this:
jdbc:mysql://localhost:3306/database_name?enabledTLSProtocols=TLSv1.2
For testing/development purposes (not recommended for production) you can also try:
jdbc:mysql://localhost:3306/database_name?useSSL=false&allowPublicKeyRetrieval=true
In my case, I needed to do a replacement of Localhost to the actual database server IP address
Instead of
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DBname", "root", "root");
I needed
Connection con = DriverManager.getConnection(
"jdbc:mysql://192.100.0.000:3306/DBname", "root", "root");
I catch this exception when Java out of heap. If I try to put in RAM many data items - first I catch "Communications link failure" and next "OutOfMemoryError".
I logged it and I decrease memory consumption (delete 1/2 data) and all ok.
This com.mysql.jdbc.exceptions.jdbc4.CommunicationsException exception occurs if your database connection is idle for long time.
This idle connection returns true on connection.isClosed(); but if we try to execute statement then it will fire this exception so I will suggest to go with database pooling.
In my case, turn out to be that the version of mysql-connector-java was too old.
In my demo, I somehow use mysql-connector-java like this:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
But in the develop environment, I use this:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
And my MySQL version was 5.1.48(yes, it is old, just for mimic the product version). So I met the same error.
Since the reason is found, the solution is found, too. Match the version!
I've been having the same problem for hours. I'm using MAMP Server
Instead of using localhost:[Apache Port], use your MySQL port.
Below is the default MySQL Port for MAMP server.
String url = "jdbc:mysql://localhost:8889/db_name";
Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);
Add this
useSSL=false&allowPublicKeyRetrieval=true
jdbc:mysql://localhost:3306/cloudapp?useSSL=false&allowPublicKeyRetrieval=true
https://youtu.be/ray3YvnIohM
This error may also happen if Java tries to connect to MySQL over SSL, but something goes wrong. (In my case, I was configuring Payara Server 5.193.1 connection pools to MySQL.)
Some people suggested setting useSSL=false. However, since Connector/J version 8.0.13, that setting is deprecated. Here's an excerpt from MySQL Connector/J 8.0 Configuration Properties:
sslMode
By default, network connections are SSL encrypted; this property permits secure connections to be turned off, or a different levels of security to be chosen. The following values are allowed: DISABLED - Establish unencrypted connections; PREFERRED - (default) Establish encrypted connections if the server enabled them, otherwise fall back to unencrypted connections; REQUIRED - Establish secure connections if the server enabled them, fail otherwise; VERIFY_CA - Like REQUIRED but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates; VERIFY_IDENTITY - Like VERIFY_CA, but additionally verify that the server certificate matches the host to which the connection is attempted.
This property replaced the deprecated legacy properties useSSL, requireSSL, and verifyServerCertificate, which are still accepted but translated into a value for sslMode if sslMode is not explicitly set: useSSL=false is translated to sslMode=DISABLED; {"useSSL=true", "requireSSL=false", "verifyServerCertificate=false"} is translated to sslMode=PREFERRED; {"useSSL=true", "requireSSL=true", "verifyServerCertificate=false"} is translated to sslMode=REQUIRED; {"useSSL=true" AND "verifyServerCertificate=true"} is translated to sslMode=VERIFY_CA. There is no equivalent legacy settings for sslMode=VERIFY_IDENTITY. Note that, for ALL server versions, the default setting of sslMode is PREFERRED, and it is equivalent to the legacy settings of useSSL=true, requireSSL=false, and verifyServerCertificate=false, which are different from their default settings for Connector/J 8.0.12 and earlier in some situations. Applications that continue to use the legacy properties and rely on their old default settings should be reviewed.
The legacy properties are ignored if sslMode is set explicitly. If none of sslMode or useSSL is set explicitly, the default setting of sslMode=PREFERRED applies.
Default: PREFERRED
Since version: 8.0.13
So, in my case, setting sslMode=DISABLED was all I needed to resolve the issue.
This was on a test machine. But for production, the secure solution would be properly configuring the Java client and MySQL server to use SSL.
Notice that by disabling SSL, you might also have to set allowPublicKeyRetrieval=true. (Again, not a wise decision from security standpoint). Further information is provided in MySQL ConnectionString Options:
AllowPublicKeyRetrieval
If the user account uses sha256_password authentication, the password must be protected during transmission; TLS is the preferred mechanism for this, but if it is not available then RSA public key encryption will be used. To specify the server’s RSA public key, use the ServerRSAPublicKeyFile connection string setting, or set AllowPublicKeyRetrieval=True to allow the client to automatically request the public key from the server. Note that AllowPublicKeyRetrieval=True could allow a malicious proxy to perform a MITM attack to get the plaintext password, so it is False by default and must be explicitly enabled.
I might be barking up the wrong tree here, but your exception seems to indicate your MySQL server isn't available.
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failureThe last packet sent successfully to the server was 0
milliseconds ago. The driver has not received any packets from the server. at...
What happens if you try (from the terminal)
mysql -u username -p
You will be prompted for the password associated with the username. After you give the correct password does the mysql client connect?
You may have to start MySQL from the Preferences if not. You can also set it to run at startup.
Earlier answers are appropriate . But , I would also like to point towards a more generic issue.
I faced similar issue and the reason was a network restriction of my company.
Same connection was getting successful when I was in any other network.
I got the same error because I was trying to run my program without starting mysql server.
After starting the mysql server, everything went right.
Please update your IP address in /etc/mysql/my.cnf file
bind-address = 0.0.0.0
Restart mysql deamon and mysql services.
Download MySQL-JDBC-Type-4-Treiber (i.g. 'mysql-connector-java-5.1.11-bin.jar' from 'mysql-connector-java-5.1.11.zip') at Mysql.
You need to inculde the driver jar during compile- and runtime in your classpath.
Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
// edit the jdbc url
Connection conn = DriverManager.getConnection( "jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName", username, password );
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery( "select * from table" );
My same problem is solved by the following steps:
Go to my.cnf
vi /etc/mysql/my.cnf
Modify its bind-address
"bind-address = 0.0.0.0"
Restart MySQL
sudo /etc/init.d/mysql restart
If you are using WAMP or XAMP server to install mysql database.
Then you have to explicitly start mysql sever other wise it will show
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure while connecting with database
i solved this problem in a easy way, that worked for me. i had the seme problem "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure". In my db.properties file i had this : url:jdbc:mysql://localhost:90/myDB,
only removed the port url , resulting in this manner url:jdbc:mysql://localhost/myDB and that worked for me.
Thats happened to me when I changed the mysql port from 3306 to 3307 in my.ini and the php.ini files but after changing the ports (3307->3306) back it worked fine again.
If you changed your port, you get this kind of error "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure"
Please check your port number
Try to change localhost to 127.0.0.1.
The localhost would be resolved to ::1. And MySQL cannot be connected via IPv6 by default.
And here is the output of telnet localhost 3306:
$ telnet localhost 3306
Trying ::1...
And there is no response from MySQL server.
Of course, please make sure your MySQL server is running.
dbhost=jdbc:mysql://172.18.23.100:3306/yourdatabase?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
user=root
password=Password#321
con = DriverManager.getConnection(dbhost, user, password);
if mysql version 8 or higher user updated connector
In my case, turn out to be that the version of mysql-connector-java was different.
I just changed mysql jdbc to maria jbdc
Old jdbc driver
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
New Jdbc driver
<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.6.2</version>
</dependency>
Just experienced this.
Got to make it work by:
(this can be placed in the static block intializer)
static{ // would have to be surrounded by try catch
Class.forName("com.mysql.jdbc.Driver"); // this will load the class Driver
}
Also by obtaining the connection through:
conn = DriverManager.getConnection(DBURL,<username>,<password>);
instead of specifying the login parameters
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/projects?user=user1&password=123");
Regards.
It could be a simple jar problem. may be you are using a old mysql-connector-java-XXX-bin.jar which is not supported by your current mysql version. i used mysql-connector-java-5.1.18-bin.jar as i am using mysql 5.5 and this problem is resolved for me.
My firewall was blocking post 3307 which my MySQL listening on. So I changed port from 3307 to 3306.Then I can successfully connect to a database.
I was receiving multiple errors such as:
CommunicationsException: Communications link failure
java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference at.
I had to add:
In AndroidManifest.xml include <uses-permission android:name="android.permission.INTERNET"/> just after the opening manifest tag.
Add the JDBC driver into your Gradle (or Maven) dependencies.
Sample jdbc connection class file. simply call the getConnection method when you want to get a connection. include related mysql-connector.jar
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public Connection getConnection() {
Connection con = null;
String dbhost;
String user;
String password;
// get properties
dbhost="jdbc:mysql://localhost:3306/cardmaildb";
user="root";
password="123";
System.out.println("S=======db Connecting======");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbhost, user, password);
//if you are facing with SSl issue please try this
//con = DriverManager.getConnection("jdbc:mysql://192.168.23.100:3306/cardmaildb?useUnicode=yes&characterEncoding=UTF-8&useSSL=false",user, password);
} catch (Exception e) {
System.err.println("error in connection");
e.printStackTrace();
}
System.out.println("E=======db Connecting======");
return con;
}
public static void main(String[] args) {
new DBConnection().getConnection();
}
}
For Remote Call to Mysql
Add remote user to Mysql from for exemple IP=remoteIP :
mysql -u xxxx -p //local coonection to mysql
mysql> GRANT ALL PRIVILEGES ON *.* TO 'theNewUser'#'remoteIP' IDENTIFIED BY 'passWord';
//Query OK, 0 rows affected (xx sec)
mysql> FLUSH PRIVILEGES;
//Query OK, 0 rows affected
Allow remote access to Mysql (by default all externall call is not allowed):
Edit
/etc/mysql/mysql.conf.d/mysqld.cnf or /etc/mysql/my.cnf
Change line: bind-address = 127.0.0.1 to
bind-address = 0.0.0.0
Restart Mysql: /etc/init.d/mysql restart
For The latest version of JDBC Driver, the JDBC :
jdbc.url='jdbc:mysql://remoteIP:3306/yourDbInstance?autoReconnect=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC'
jdbc.user='theNewUser'
Open file /etc/mysql/my.cnf:
change below parameter from
`bind-address = 127.0.0.1
to
bind-address = 0.0.0.0 #this allows all systems to connect
Run below command in mysql for specific IP Address->
grant all privileges on dbname.* to dbusername#'192.168.0.3' IDENTIFIED BY 'dbpassword';
If you want to give access to all IP Address, run below command:
grant all privileges on dbname.* to dbusername#'%' IDENTIFIED BY 'dbpassword';
I have the same connection error:
The problem I have is I used MySQL 8.0.15 but the Java Connector is 5.x.x.
Below is how I fixed it.
1. download the 8.0.15. from Maven repository:
https://search.maven.org/search?q=g:mysql%20AND%20a:mysql-connector-java
In the Eclipse IDE, select the "Referenced Libraries" in Explorer
Right Mouse Button > Build Path > Configure Build Path
a. remove the "mysql-connector-5.x.jar"
b. Click "Add External JARs..." and select mysql-connector-java-8.0.15.jar.
Re-run it, the problem went away.

jdbc mysql giving me NumberFormatException

I am trying to connect to a remote mysql database but I get the following error
java.sql.SQLException: Cannot connect to MySQL server on biomancy.com:3306. Is
here a MySQL server running on the machine/port you are trying to connect to? (
ava.lang.NumberFormatException)
at org.gjt.mm.mysql.Connection.connectionInit(Unknown Source)
at org.gjt.mm.mysql.jdbc2.Connection.connectionInit(Unknown Source)
at org.gjt.mm.mysql.Driver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at cliche.database.ClicheDBManager.<init>(ClicheDBManager.java:33)
at cliche.server.ClicheExtension.init(ClicheExtension.java:43)
The code in the init function trigger this chain is simply:
myConnection = DriverManager.getConnection(connectionString, user, pass);
I can connect to the database using the commandline mysql from this same computer just fine using the same credentials, and it let me know I had the password wrong when I tried with the wrong password.
Thank you in advance for your help, I hope I gave enough information here.
My best guess is the driver is not the right version. Double check that you have a current version of the driver or try a different driver. Also double check that mysql running on the default port (3306).

Categories

Resources