NullPointerException in Hibernate [duplicate] - mysql

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

Related

Got "java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long" error [duplicate]

When connecting to MySQL, I get an error (see below).
Click here for code
I get this output:
run:
Now connecting to databse...
java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ConnectionImpl.buildCollationMapping(ConnectionImpl.java:1062)
at com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3556)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2513)
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 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:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:317)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at dbms_basic.Dbms_Basic.main(Dbms_Basic.java:28)
Caused by: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
at com.mysql.jdbc.ConnectionImpl.buildCollationMapping(ConnectionImpl.java:1007)
... 15 more
BUILD SUCCESSFUL (total time: 0 seconds)
How can I solve this?
Your error clearly says casting is not possible, because a java.math.BigInteger class instance is not an instance of java.lang.Long class.
Now the question arises who is doing casting at what level, when we ask the JDBC driver to make a connection, it is doing lot of work behind the scene before it actually give us back the proper working object of connection.
The problem seems with your version of MySQL in combination with your version of mysql-connector.jar. Try a newer version of MySQL Connector/J (see https://dev.mysql.com/downloads/connector/j/ for the latest version), for example upgrade to 5.1.47 or 8.0.12 if you are using an older version.
This issue is not there with 5.1.45 as mentioned in the above comments. Available to download at,
https://repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.45/
Another way, because changing the version from mysql does not worked for me, for help another people:
Long.parseLong(String.valueOf(item[0]);
There is a miss-match between your MySQL version, which might be the latest 8.0.19, but the MySQL driver file is older version may be 5.1.23, which is generally available with the NetBeans IDE. To overcome this, download the mysql-connector-java-5.1.48.jar from this link in your PC download connector/j 5.1.48 zip file
(4.6MB)
Now right-click on project name in the netbeans IDE, go to services, in that choose 'Libraries', in it choose 'Add library', then don't opt for available libraries( the drop-down menu will list a JDBCDriver file which has 'mysql-connector-java-5.1.23.jar' file inside it, which is an older version, this is causing the miss-match). Therefore, instead click on 'Create Library', now give it any name of your choice, then click the create button, a browse window will pop-up, go to the directory where you have downloaded the 'mysql-connector-java-5.1.48.zip' folder, open it and select the java jar file 'mysql-connector-java-5.1.48.jar' and click 'ok'. The library folder of your project tree will now show 'JDBCDriver-mysql-connector-java-5.1.48.jar' added in the list of libraries(JDK and Tomcat) . Now try connecting to your database again by clicking on the 'run' button, go to the JSP link, and you see that this time you are connected.
For me updating the connector wasn't enough, I also had to complete my DriverManager.getConnection() url parameter with all the arguments, even if the error message was not mentionning this issue.
In my case this parameters were needed :
"jdbc:mysql://127.0.0.1:3306/database?zeroDateTimeBehavior=convertToNull&serverTimezone=UTC"
Connector : mysql-connector-java-8.0.17.jar
mysql version : 8.0.17
Using java on netbeans.
This is a common issue when you use outdated/unsupported mysql connector driver. If youre using x86 version of Netbeans, your driver will usually be found in the Program(x86) folder an not the Program folder. something like this "C:\Program Files (x86)\MySQL\Connector J 8.0\mysql-connector-java-8.0.23.jar"

Connecting NetBeans to MySQL [duplicate]

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());
}

MySQL JDBC driver not working with GWT Eclipse Project

My GWT application does not seem to find mysql-connector-java-5.1.22-bin.jar.
Im using the Google App Engine.
I have set the jar in Project->RIghtClick->Properties->Java Build Path->Libraries->mysql-connector-java-5.1.22-bin.jar. I also added the "MySQL JDBC Driver". The $CLASSPATH is set correctly too (i dont think it matters because Im running the application in Eclipse).
I have tested the same code on command line and it works like a charm.
$ java -cp ~/mysql-connector-java-5.1.22/mysql-connector-java-5.1.22-bin.jar:. JDBCExample
-------- MySQL JDBC Connection Testing ------------
MySQL JDBC Driver Registered!
You made it, take control your database now!
When I run the Web Application in Eclipse, I get this
Exception:
-------- MySQL JDBC Connection Testing ------------
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
ClassNotFound - Where is your MySQL JDBC Driver?com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:207)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at com.startupweekend.server.GreetingServiceImpl.readDB(GreetingServiceImpl.java:65)
at com.startupweekend.server.GreetingServiceImpl.greetServer(GreetingServiceImpl.java:21)
Code:
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFound - Where is your MySQL JDBC Driver?" + e.getMessage());
e.printStackTrace();
return;
}
I'm not completely sure, but you should just put the mysql driver in your WEB-INF/lib folder and then right click -> add to build path. That should make it work.
Bear in mind that in GAE you cannot use common relational databases, you can only use Google CloudSQL.
You don't need the App Engine, just use GWT compile when you're ready for your war file. In any case, right click project folder -> properties -> Google -> App Engine -> uncheck 'Use Google App Engine'. Make sure the mysql-connector is in your lib folder. Enjoy your favorite relational database, and more.
Cheers

com.mysql.jdbc.Driver not found with mysql connector in buildpath

I use Eclipse juno. I have mysql-connector-java-5.1.22-bin.jar in my buildpath and i try to establish a DB connection to my mysql database. Here is my code
public Connection getConnectionToDB() {
try {
Class.forName(driver);
Connection con = DriverManager.getConnection(url + dbName,
userName, password);
return con;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
When i debug it i found out the problem is at:
Class.forName(driver);
i also tried replacing it with:
Class.forName(driver).newInstance();
At this line, it breaks out to the exception and throws this exception:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at main.jdbc.BaseJdbc.getConnectionToDB(BaseJdbc.java:18)
at main.jdbc.UserDriverJdbc.queryUserById(UserDriverJdbc.java:15)
at main.drivers.UserDriver.findUserById(UserDriver.java:50)
at main.drivers.UserDriver.isLoginValid(UserDriver.java:56)
at main.controllers.LoginController.doPost(LoginController.java:33)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:164)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.__invoke(StandardHostValve.java:164)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
The answer was quite tricky for me to find but i figure it out. It was ofcourse classpath problem.
If you ever encounter a problem like this and try to solve it inside eclipse, go to
eclipse -> window -> preferences -> java -> buildpath -> classpath
and add the
"mysql-connector-java-5.1.22-bin.jar"
as new variable. Name it whatever you like. Hope this helps.
You need to make sure you have the proper libraries and jar files loaded in your project. I dealt with this a lot when working with postgresql. I would think you're just missing the jar file.
This was my problem which was answered here:
SO Link
"If this code works in your J2SE it means you need to have a JAR file somewhere containing com.mysql.jdbc.Driver class (so called JDBC driver). This JAR needs to be visible in Tomcat. So, I would suggest to place mysql-jdbc.jar at physical location to /WEB-INF/lib directory of your project." From
I've been looking for a solution everywhere. Maybe this is not your solution, but using Eclipse i was exporting as a JAR file and got same exception, but then exported as "Runnable JAR"and it worked.
If you use netbeans then do the followings:
go to your application>>>libraries>>add jar (by right click)>> "mysql-connector-java-5.1.22-bin.jar"
In Your Eclipse Go to Windows->Preferences->Java->BuildPath->ClassPathVariables->New
Now Add Your Mysql-Connector jar file what you downloaded From Mvn repository or anywhere ...Now ApplyAndClose ...restart the server it will work...
Note: If You are using Servlet then use eclipse from the package not from the installer..If you will use the installer you will get lot of problem

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools? [duplicate]

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 6 years ago.
I am trying to create a connection to my database, when I put test my code using the main method, it works seamlessly. However, when trying to access it through Tomcat 7, it fails with error:
No suitable driver found for jdbc:mysql://localhost/dbname.
I am using pooling. I put in mysql connector (5.1.15), dbcp (1.4) , and pool(1.4.5) libraries in WEB-INF/lib and in .classpath as well. I am using Eclipse IDE. My code for the database driver is:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.tomcat.dbcp.dbcp.ConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.DriverManagerConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.PoolingDriver;
import org.apache.tomcat.dbcp.pool.impl.GenericObjectPool;
public class DatabaseConnector {
public static String DB_URI = "jdbc:mysql://localhost/dbname";
public static String DB_USER = "test";
public static String DB_PASS = "password";
// Singleton instance
protected static DatabaseConnector _instance;
protected String _uri;
protected String _username;
protected String _password;
/**
* Singleton, so no public constructor
*/
protected DatabaseConnector(String uri, String username, String password) {
_uri = uri;
_username = username;
_password = password;
GenericObjectPool connectionPool = new GenericObjectPool(null);
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
_uri, _username, _password);
PoolableConnectionFactory poolableConnectionFactory =
new PoolableConnectionFactory(connectionFactory, connectionPool,
null, null, false, true);
PoolingDriver driver = new PoolingDriver();
driver.registerPool("test", connectionPool);
}
/**
* Returns the singleton instance
*/
public static DatabaseConnector getInstance() {
if (_instance == null) {
_instance = new DatabaseConnector(DB_URI, DB_USER, DB_PASS);
}
return _instance;
}
/**
* Returns a connection to the database
*/
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
throw new RuntimeException(e);
}
return con;
}
}
Start of my stack trace:
Apr 5, 2011 9:49:14 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Login] in context with path [/Project]
threw exception
java.lang.RuntimeException: java.sql.SQLException:
No suitable driver found for jdbc:mysql://localhost/dbname
What is causing this error?
Try putting the driver jar in the server lib folder. ($CATALINA_HOME/lib)
I believe that the connection pool needs to be set up even before the application is instantiated. (At least that's how it works in Jboss)
The reason you got this error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/dbname
Is because you forgot to register your mysql jdbc driver with the java application.
This is what you wrote:
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
throw new RuntimeException(e);
}
Should be this:
Connection con = null;
try {
//registering the jdbc driver here, your string to use
//here depends on what driver you are using.
Class.forName("something.jdbc.driver.YourFubarDriver");
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
throw new RuntimeException(e);
}
You'll have to read the manual on your specific mysql jdbc driver to find the exact string to place inside the the Class.forName("...") parameter.
Class.forName not required with JDBC v.4
Starting with Java 6, Class.forName("something.jdbc.driver.YourFubarDriver") is not necessary anymore if you use a recent (JDBC v.4) driver. For details read this: http://onjava.com/pub/a/onjava/2006/08/02/jjdbc-4-enhancements-in-java-se-6.html
I had the same problem using Tomcat7 with mysql-connector-java-5.1.26 that I put in both my $CATALINA_HOME/lib and WEB-INF/lib, just in case. But it wouldn't find it until I used either one of these two statements before getting the connection:
DriverManager.registerDriver(new com.mysql.jdbc.Driver ());
OR
Class.forName("com.mysql.jdbc.Driver");
I then followed up with removing mysql-connector-java-5.1.26 from $CATALINA_HOME/lib and the connection still works.
When running tomcat out of eclipse it won't pick the lib set in CATALINA_HOME/lib, there are two ways to fix it. Double click on Tomcat server in eclipse servers view, it will open the tomcat plugin config, then either:
Click on "Open Launch Config" > Classpath tab set the mysql connector/j jar location.
or
Server Location > select option which says "Use Tomcat installation (take control of Tomcat installation)"
I had the mysql jdbc library in both $CATALINA_HOME/lib and WEB-INF/lib, still i got this error . I needed Class.forName("com.mysql.jdbc.Driver"); to make it work.
add the artifact from maven.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
I'm running Tomcat 7 in Eclipse with Java 7 and using the jdbc driver for MSSQL sqljdbc4.jar.
When running the code outside of tomcat, from a standalone java app, this worked just fine:
connection = DriverManager.getConnection(conString, user, pw);
However, when I tried to run the same code inside of Tomcat 7, I found that I could only get it work by first registering the driver, changing the above to this:
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
connection = DriverManager.getConnection(conString, user, pw);
Use:
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Registro exitoso");
} catch (Exception e) {
System.out.println(e.toString());
}
DriverManager.getConnection(..
Bro, you can also write code as below:
import java.sql.*;
import java.io.*;
public class InsertDatabase {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Maulik","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from Employee");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
I also had the same problem some time before, but I solved that issue.
There may be different reasons for this exception.
And one of them may be that the jar you are adding to your lib folder may be old.
Try to find out the latest mysql-connector-jar version and add that to your classpath.
It may solve your issue. Mine was solved like that.
I had the same problem, all you need to do is define classpath environment variable for tomcat, you can do it by adding a file, in my case C:\apache-tomcat-7.0.30\bin\setenv.bat, containing:
set "CLASSPATH=%CLASSPATH%;%CATALINA_HOME%\lib\mysql-connector-java-5.1.14-bin.jar"
then code, in my case:
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "root", "");
works fine.
if you are using netbeans you must add Mysql JDBC driver in the library list of the project, in the properties of your project
Most of time it happen because two mysql-connector-java-3.0.14-production-bin.jar file.
One in lib folder of tomcat and another in classpath of the project.
Just try to remove mysql-connector-java-3.0.14-production-bin.jar from lib folder.
This way it is working for me.
From what i have observed there might be two reasons for this Exception to occur:
(1)Your Driver name is not spelled Correctly.
(2)Driver hasn't been Associated Properly with the Java Project
Steps to follow in Eclipse:
(1)Create a new Java Project.
(2)copy The connector Jar file
(3)Right Click on the Java project and paste it there.
(4)Right click on the Java project -> Properties ->Java Build Path - >libraries-> Add Jar ->choose ur project(select the jar file from dropdown) and click ok.
The solution is straightforward.
Make sure that the database connector can be reached by your classpath when running (not compiling) the program, e.g.:
java -classpath .;c:\path\to\mysql-connector-java-5.1.39.jar YourMainClass
Also, if you're using an old version of Java (pre JDBC 4.0), before you do DriverManager.getConnection this line is required:
Class.forName("your.jdbc.driver.TheDriver"); // this line is not needed for modern Java
When developing using Ubuntu (Xubuntu 12.04.1) I 'HAD' to do the following:
Using
Eclipse Juno (downloaded, not installed via the software centre),
Tomcat 7 (downloaded in a custom user directory) also added as a Server in Eclipse,
Dynamic Web Project with a 3.0 Servlet,
MySQL Server on localhost configured and tested with user and password (make sure to test)
MySQL connector driver 5.1.24 jar,
I 'HAD', and I repeat 'HAD', to us the Class.Load("com.mysql.jdbc.Driver") statement along with adding the connector driver.jar to be in the web project lib folder for it to work in this situation.
IMPORTANT!!: after you copy the driver.jar to the lib make sure you refresh your project in Eclipse before running the servlet via Tomcat.
I did try adding the connector driver jar file via the Build Path with and without ClassLoad but it did not work!
Hope this helps anyone starting development with this specific situation: the Java community provides a 'LOT' of documentation but there are so many variables its hard to cover all of them and it makes things very hard on the new guy.
I think if someone could explain why Class.Load is required here (in this situation) it would be beneficial.
Enjoy
Since no one gave this answer, I would also like to add that, you can just add the jdbc driver file(mysql-connector-java-5.1.27-bin.jar in my case) to the lib folder of your server(Tomcat in my case). Restart the server and it should work.
Put mysql-connector-java-5.0.8-bin.jar in $CATALINA_HOME/lib
Check for typo in connection url, example
"jdbc:mysql://localhost:3306/report" ('report' here is the db name)
Make sure to use machine name(example : localhost instead of ip address(127.0.0.1))
Add the driver class to the bootstrapclasspath. The problem is in java.sql.DriverManager that doesn't see the drivers loaded by ClassLoaders other than bootstrap ClassLoader.
From other stackoverflow thread:
"Second. Make sure that you have MySQL JDBC Driver aka Connector/J in JMeter's classpath. If you don't - download it, unpack and drop mysql-connector-java-x.xx.xx-bin.jar to JMeter's /lib folder. JMeter restart will be required to pick the library up"
Please be sure that .jar file is added directly to the lib folder.
You can stick the jar in the path of run time of jboss like this:
C:\User\user\workspace\jboss-as-web-7.0.0.Final\standalone\deployments\MYapplicationEAR.ear\test.war\WEB-INF\lib
ca marche 100%