Connecting NetBeans to MySQL [duplicate] - mysql

This question already has answers here:
Solving a "communications link failure" with JDBC and MySQL [duplicate]
(25 answers)
Closed 7 months ago.
I've looked all over and tried everything I've been able to find on this so I'm making a post in case my issue is something strange.
MySQL workbench can use the server for queries and updates just fine. The notifier shows the server is running.
I've tried using Eclipse Juno and Kepler and got eclipse SQL State: 08S01 error 0. Zero packets were sent successfully and there was no response from the server.
I redownloaded Connector/J to make sure there wasn't an error from a download hiccup. Didn't improve.
I changed to Netbeans to make sure it wasn't just Eclipse and something on my system. No successful packets sent and nothing received.
I tested to make sure the server was on and the correct port was being used by telnet in command prompt and as expected it asks for password input like it should. I used Wire Shark to see what the packet data looked like. It looked like the server was listening on the correct port and MySQL workbench was using the right port.
I'm at a loss for what is wrong. I even updated to Windows 7 to make sure it wasn't a driver authentication issue with Vista.
I used this code in NetBeans:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MySQLTest {
public static void main(String[] args)
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("1");
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.0:3306/", "root", "wonderwoman");
System.out.println("2");
con.close();
System.out.println("We made it!");
} catch (SQLException ex) {
Logger.getLogger(MySQLTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(MySQLTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(MySQLTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(MySQLTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And eventually received this:
Oct 22, 2013 8:59:20 PM rad.MySQLTest main
SEVERE: null
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:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:357)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2482)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2519)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2304)
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:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.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:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at rad.MySQLTest.main(MySQLTest.java:21)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:241)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:259)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:307)
... 15 more
What else should I try? It looks like it's getting to the server and than everything is just bouncing off. I've turned off my firewall, I'm not using a proxy, kind of pulling my hair out here.

I think you are running mysql on your local machine if so append your database name to the connection string and try
e.g. "jdbc:mysql://127.0.0.1:3306/databasename"
or try "jdbc:mysql://localhost:3306/databasename"
You are using 127.0.0.0 as your ip address but normally localhost is 127.0.0.1 not 127.0.0.0

Add the MySql_connetor.bin file to your project Library, then clean and build, and run.

I just do a quick search and see this video tutorial, maybe you do something wrong in step by step. Hope it 's helpful for your need http://magentoexpertforum.com/showthread.php/10268-Connect-Netbean-to-MySQL

Hi I just had the exact same problem, up until now my MySQL server was being connected to netbeans fine, then all of a sudden it stopped working. I checked my my.config file in the bin folder and for some reason the port had changed from 3306 to 6033, so you can either re-register your MySQL with the new port number, or change the port number in the config file.

Try this code :
try {
Class.forName("java.sql.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/db_name","username","password");
Statement stmt = con.createStatement();
///your furthercode acc. to your project
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage());
}

Related

NullPointerException in Hibernate [duplicate]

I'm trying to connect to a database I created with MySQL in my Java program, but it always fails.
For the sake of example, here is my code:
import java.sql.*;
public class Squirrel {
public static void main(String[] args) {
String user;
String password;
Connection connection;
Statement statement;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306", user, password);
statement = connection.createStatement();
// Other code
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
I am able to connect to the database from within IntelliJ and have added the mysql-connector-java-5.1.40.jar added to the project, but each time I run the program DriverManager.getConnection() throws this:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2330)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:678)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:229)
at Squirrel.main(Squirrel.java:12)
Caused by: java.lang.NullPointerException
at com.mysql.jdbc.ConnectionImpl.getServerCharset(ConnectionImpl.java:2997)
at com.mysql.jdbc.MysqlIO.sendConnectionAttributes(MysqlIO.java:1934)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1863)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
... 13 more
It might be because you're using an older version of the MySQL driver.
You should try using the newest version.
To get the newest version, you can check https://mvnrepository.com/artifact/mysql/mysql-connector-java
As of right now, the newest version is 8.0.11. You can download it here or add this to your pom.xml:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
Update
Upon further investigation, it seems that it's because of a change that was introduced in MySQL 8.0.1:
The issue you reported is related to the changes introduced in MySQL
8.0.1 wrt the character sets and collations support, with the addition of now being 'utf8mb4' the default char set. Such changes broke the
way Connector/J initializes connections.
As you know this was fixed in Connector/J 5.1.41 and I'm sure you
already updated your library.
reference
Like mentionned above, an alternative fix to your problem would have been to use the 5.1.41 instead of 5.1.40.
Sounds like a potential version mismatch or outdated client. When you run it outside the IDE you may be pulling in the wrong version. I'd make sure the client is on the latest version or similar to the version used by the server.
I was importing the wrong version of mysql-connector. Changed the following
#Grab('mysql:mysql-connector-java:5.1.25')
to
#Grab('mysql:mysql-connector-java:5.1.46')
and everything worked as expected.
I've tried the above and it doesn't work. Then I checked in my .m2 folder and I noticed that there is a version 5.1.32 and version 8.0.19 mysql connector. However, when I tried to delete the folders, I'm not able to delete version 5.1.32 while the app is running. Obviously it means that version 5 is being in used somehow, eventhough in pom I've specified to use version 8.0.19.
So I just need to invalidate and restart from IntelliJ and voila.
If you call the IP address 127.0.0.1/localhost then you are communicating with the localhost – in principle, with your own computer.This issue also appears when you don't have localhost configured
For Linux systems
Add/Edit "127.0.0.1 localhost" under /etc/hosts if its missing.
For Windows system
Add/Edit under C:windows/system32/drivers/etc/hosts if its missing.
For more details on localhost

MySQLNonTransientConnectionException when getting ssl connnection to mysql from tomcat application

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException been raised when attempting to make an SSL connection to MySQL from a tomcat-based application.
I have tried the same code in a Java class in the main method without tomcat (like a Java project in eclipse). This program works fine, i.e. I am able to get an SSL connection to the database.
Error code:
DriverManager.getConnection("jdbc:mysql://localhost:3306/ibisdb74?verifyServerCertificate=true&useSSL=true&requireSSL=true&clientCertificateKeyStoreUrl=file:/home/directoryA/mysql_certs_latest4/keystore&clientCertificateKeyStorePassword=mypass&trustCertificateKeyStoreUrl=file:/home/directoryA/mysql_certs_latest4/truststore&trustCertificateKeyStorePassword=mypass","root","root");
Exception trace:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Cannot open file:/home/gom7kor/mysql_certs_latest4/truststore [keystore password was incorrect]
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
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:1014)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.ExportControlled.getSSLSocketFactoryDefaultOrConfigured(ExportControlled.java:224)
at com.mysql.jdbc.ExportControlled.transformSocketToSSLSocket(ExportControlled.java:80)
at com.mysql.jdbc.MysqlIO.negotiateSSLConnection(MysqlIO.java:5170)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1676)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1250)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2465)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2498)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2283)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:822)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:317)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
Caused by: java.io.IOException: keystore password was incorrect
at java.base/sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:2108)
at java.base/sun.security.util.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:243)
at java.base/java.security.KeyStore.load(KeyStore.java:1479)
at com.mysql.jdbc.ExportControlled.getSSLSocketFactoryDefaultOrConfigured(ExportControlled.java:204)
... 23 more
Caused by: java.security.UnrecoverableKeyException: failed to decrypt safe contents entry: javax.crypto.BadPaddingException: pad block corrupted
... 27 more
I looked for a successful encrypted connection without an exception, even in the tomcat based application.
PS: I am getting this exception with a tomcat based application, but not in non-tomcat applications. And I am using jdk 11 and tomcat 9.

Interesting MySQL error creating a Keycloak project on Openshift

I try to create a Keycloak app that uses MySQL.
Hello,
I just want to create a Keycloak app on Openshift which is using MySQL.
1- I have created an Openshift project.
2- I created a MySQL instance (as I am not sure if this template automatically creates one) with these credentials:
user: keycloak
password: password
db : keycloak
3- Then I have copied this: Openshift-template:
https://github.com/jboss-dockerfiles/keycloak/blob/master/openshift-examples/keycloak-https.json
But I just changed Keycloak image: "image": "jboss/keycloak:4.8.1.Final"
(as keycloak-openshift image deprecated.)
And I am getting this error:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Cannot load connection class because of underlying exception: 'java.lang.NumberFormatException: For input string: "tcp:"'.
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.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:338)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:321)
... 55 more
Caused by: java.lang.NumberFormatException: For input string: "tcp:"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at com.mysql.jdbc.NonRegisteringDriver.port(NonRegisteringDriver.java:825)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
... 56 more
I have solved my problem but I think it is most probably a bug as we cannot relate a MySQL app named "mysql" to this Keycloak version and we cannot set DB_ADDR as "mysql". (Which is reported by a user (cjohn001), but not solved)
Just a note for the people who may have the same problem in future:
It is the manipulated Openshift template. I added some extra environment variables and parameters to solve this problem:
https://github.com/helpfularmy/ssoha/blob/master/keycloak-https.json

spring-boot web app loses ability to connect to MySQL / RDS after a while

I have a normal spring boot 1.2.x web app with an embedded Tomcat 7.x container and connected to an RDS instance (running MySQL 5.6). If the application is idle for a period of time (8 hours?) and then it receives a request it throws the following exception
** BEGIN NESTED EXCEPTION **
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException
MESSAGE: The last packet successfully received from the server was39320 seconds ago.The last packet sent successfully to the server was 39320 seconds ago, whi
ch is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your ap
plication, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this proble
m.
STACKTRACE:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was39320 seconds ago.The last packet sent succe
ssfully to the server was 39320 seconds ago, which is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or t
esting connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection pr
operty 'autoReconnect=true' to avoid this problem.
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:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
... trimmed more of the stacktrace ...
Caused by: java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
at java.net.SocketOutputStream.write(SocketOutputStream.java:159)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3227)
... 119 more
** END NESTED EXCEPTION **
In my application.yml (where configurations for datasource, hibernate, etc. can be set) I have the following (this is part of what I get when I call the management API /env
"applicationConfig: [classpath:/application.yml]#rds-profile":{
"spring.profiles":"rds-profile",
"spring.datasource.driverClassName":"com.mysql.jdbc.Driver",
"spring.datasource.url":"jdbc:mysql://rds-host:3306/mydb?user=mysqlusername&password=****",
"spring.datasource.schema":"classpath:/schema.sql",
"spring.datasource.username":"mysqlusername",
"spring.datasource.password":"******",
"spring.datasource.testOnBorrow":true,
"spring.datasource.validationQuery":"SELECT 1",
"spring.datasource.continueOnError":true,
"spring.datasource.timeBetweenEvictionRunsMillis":5000,
"spring.datasource.minEvictableIdleTimeMillis":5000,
"spring.datasource.max-active":500,
"spring.jpa.database-platform":"org.hibernate.dialect.MySQL5InnoDBDialect",
"spring.jpa.database":"MYSQL",
"spring.jpa.show-sql":false,
"spring.jpa.generate-ddl":false,
"spring.jpa.hibernate.ddl-auto":"none",
"spring.jpa.hibernate.dialect":"org.hibernate.dialect.MySQL5InnoDBDialect"
},
Curiously, when I call the management API "/configprops" I get this (I don't know if this is the root of the problem?
"spring.datasource.CONFIGURATION_PROPERTIES":{
"prefix":"spring.datasource",
"properties":{
"platform":"all",
"data":null,
"driverClassName":"com.mysql.jdbc.Driver",
"password":"******",
"url":"jdbc:mysql://rds-host:3306/mydb?user=mysqlusername&password=****",
"schema":"classpath:/schema.sql",
"username":"mysqlusername",
"jndiName":null,
"xa":{
"dataSourceClassName":null,
"properties":{
}
},
"continueOnError":true,
"sqlScriptEncoding":null,
"separator":";",
"initialize":true
}
},
The question is: given the above configurations and details, why is it that I am still getting the "wait_timeout" exception? I would expect the connections to be tested when borrowed and I would expect the JDBC connection pool to create valid connections if none are available... so why is my application running out of valid connections after (8 hours?) or inactivity?
Thank you.
If you are using auto-configuration to define RDS connection from the property file like this:
cloud.aws.rds.testdb.password=testdbpwd
cloud.aws.rds.testdb.username=testdbuser
cloud.aws.rds.testdb.databaseName=testdb
spring boot datasource auto-configuration will not work even you put these(or tomcat datasource conf) to your configuration file:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.test-on-borrow: true
spring.datasource.validation-query: SELECT 1 FROM DUAL
spring.datasource.log-validation-errors: true
I think this is the reason why you cannot validate your connections in the pool, before using them.
You need to override postProcessAfterInitialization method to set pool properties of the TomcatJdbcDataSourceFactory bean like this:
#Component
public class PoolConfiguration implements BeanPostProcessor {
#Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof TomcatJdbcDataSourceFactory) {
TomcatJdbcDataSourceFactory tomcatJdbcDataSourceFactory = (TomcatJdbcDataSourceFactory) bean;
tomcatJdbcDataSourceFactory.setTestOnBorrow(true);
tomcatJdbcDataSourceFactory.setTestWhileIdle(true);
tomcatJdbcDataSourceFactory.setValidationQuery("SELECT 1");
}
return bean;
}
}
I could not find any other solution for this.By the way this might be a bug of spring-cloud-aws-autoconfigure packet.
Good Luck!
Try using this as well
spring.datasource.test-while-idle=true
spring.datasource.validation-interval=5000

Tomcat 6 and MySQL 5.x connection error on Ubuntu

When attempting to connect to a MySQL 5.x database in a JSP webapplication running on Tomcat 6, I am getting the following exception:
org.apache.jasper.JasperException: javax.servlet.ServletException: com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: java.security.AccessControlException: access denied (java.net.SocketPermission [0:0:0:0:0:0:0:1]:3307 connect,resolve)
STACKTRACE:
java.net.SocketException: java.security.AccessControlException: access denied (java.net.SocketPermission [0:0:0:0:0:0:0:1]:3307 connect,resolve)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:151)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:280)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1699)
at com.mysql.jdbc.Connection.<init>(Connection.java:405)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:268)
at java.sql.DriverManager.getConnection(DriverManager.java:620)
at java.sql.DriverManager.getConnection(DriverManager.java:200)
at org.apache.jsp.doLogin_jsp._jspService(doLogin_jsp.java:70)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at sun.reflect.GeneratedMethodAccessor32.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:244)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAsPrivileged(Subject.java:537)
at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:276)
at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:283)
at org.apache.catalina.core.ApplicationFilterChain.access$000(ApplicationFilterChain.java:56)
at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:189)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:636)
What could be the cause and how can I fix it?
Here is the relevant bit of the trace:
java.net.SocketException MESSAGE: java.security.AccessControlException: access denied (java.net.SocketPermission [0:0:0:0:0:0:0:1]:3307 connect,resolve)
The webapp doesn't have the permission to connect/resolve the mentioned socket. You need to configure it at Tomcat level. Open /conf/catalina.policy and add the following block of code:
grant {
permission java.net.SocketPermission "localhost:3307", "connect,resolve";
};
If you want to be a bit more restrictive, e.g. granting access to a specific JDBC driver only which is present in /lib/filename.jar, then add this instead:
grant codeBase "jar:file:${catalina.home}/lib/filename.jar!/-" {
permission java.net.SocketPermission "localhost:3307", "connect,resolve";
};
Unrelated to the concrete problem, the following lines
at java.sql.DriverManager.getConnection(DriverManager.java:200)
at org.apache.jsp.doLogin_jsp._jspService(doLogin_jsp.java:70)
indicate that you're connecting the DB inside a JSP file. Maybe you're just starting and learning, but I would only mention that this is not the best practice. DB connectivity should be done in its own classes which you in turn use in a servlet class which in turn forwards to the JSP which in turn displays the results. Calling the servlet by URL should then yield the same results, but you end up with better reuseable and maintainable code.