Mysql Class Not Found Exception - java

I have some trouble connecting my remote mysql database from my rest web service running on Tomcat. I know this is common issue but I tried every way that I found on the internet. Error is: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in here: Class.forName("com.mysql.jdbc.Driver");
I am using Intellij, what I tried is, I added "mysql-connector-java-5.1.46-bin.jar" and "mysql-connector-java-5.1.46.jar" to my project as library in project structure tab of IntelliJ and I also put these files to resources folder which I marked as resources file from project structure tab. I can see these to jar file in external libraries. I added these to jar file to .classpath file and in the artifacts tab of project structure I added them as library and also as extracted directory.
But no result, same error again. Where am I doing wrong?
Edit: I am adding whole related code. I realized that if I try to run this code below in an other class that not related with rest web service and tomcat, it works. But when I try it on tomcat, It does not work.
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://(ip):3306/DatabaseName",
"(username)","password");
statement = connection.createStatement();
}catch (SQLException e){
e.printStackTrace();
}catch (ClassNotFoundException e){
e.printStackTrace();
}

Just add mysql-connector-java-5.1.46.jar in the Project Structure -> Libraries.
Make sure it appears like below screenshot.

Related

How to export a java jar file with its database? [duplicate]

What is wrong with the code there are lots of error while debugging. I am writing a code for a singleton class to connect with the database mysql.
Here is my code
package com.glomindz.mercuri.util;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySingleTon {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
private static MySingleTon myObj;
private Connection Con ;
private MySingleTon() {
System.out.println("Hello");
Con= createConnection();
}
#SuppressWarnings("rawtypes")
public Connection createConnection() {
Connection connection = null;
try {
// Load the JDBC driver
Class driver_class = Class.forName(driver);
Driver driver = (Driver) driver_class.newInstance();
DriverManager.registerDriver(driver);
connection = DriverManager.getConnection(url + dbName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return connection;
}
/**
* Create a static method to get instance.
*/
public static MySingleTon getInstance() {
if (myObj == null) {
myObj = new MySingleTon();
}
return myObj;
}
public static void main(String a[]) {
MySingleTon st = MySingleTon.getInstance();
}
}
I am new to java. Please help.
It seems the mysql connectivity library is not included in the project. Solve the problem following one of the proposed solutions:
MAVEN PROJECTS SOLUTION
Add the mysql-connector dependency to the pom.xml project file:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
Here you are all the versions: https://mvnrepository.com/artifact/mysql/mysql-connector-java
ALL PROJECTS SOLUTION
Add the jar library manually to the project.
Right Click the project -- > build path -- > configure build path
In Libraries Tab press Add External Jar and Select your jar.
You can find zip for mysql-connector here
Explanation:
When building the project, java throws you an exception because a file (the com.mysql.jdbc.Driver class) from the mysql connectivity library is not found. The solution is adding the library to the project, and java will find the com.mysql.jdbc.Driver
If you got the error in your IDE(compile-time error), you need to add your mysql-connector jar file to your libs and add this to your referenced library of project too.
If you get this error when you are running it, then probably its because you have not included mysql-connector JAR file to your webserver's lib folder.
Add mysql-connector-java-5.1.25-bin.jar to your classpath and also to your webserver's lib directory. Tomcat lib path is given as an example Tomcat 6.0\lib
Every one has written an answer but I am still surprised that nobody actually answered it by using the best simple way.
The people answer that include the jar file. But, the error will still occur.
The reason for that is, the jar is not deployed when the project is run. So, what we need to do is, tell the IDE to deploy this jar also.
The people here has answered so many times that put that jar file in the lib folder of WEB-INF. That seems okay, but why do it manually. There is simple way. Check the below steps:
Step 1: If you haven't referenced the jar file into the project then, reference it like this.
Right click on the project and go to the project properties.
Then, go to the java build path, then add external jar file via that.
But this will still not solve the problem because adding the external jar via build path only helps in compiling the classes, and the jar will not be deployed when you run the project. For that follow this step
Right click on the project and go to the project properties.
Then, go to the Deployment Assembly then press Add , then go to the java build path entries and add your libraries whether it is jstl, mysql or any other jar file. add them to deployment.
Below are the two pictures which display it.
For Gradle-based projects you need a dependency on MySQL Java Connector:
dependencies {
compile 'mysql:mysql-connector-java:6.0.+'
}
You will have to include driver jar for MySQL MySQL Connector Jar in your classpath.
If you are using Eclipse:
How to add dependent libraries in Eclipse
If you are using command line include the path to the driver jar using the -cp parameter of java.
java -cp C:\lib\* Main
check for jar(mysql-connector-java-bin) in your classpath download from here
JDBC API mostly consists of interfaces which work independently of any database. A database specific driver is required for each database which implements the JDBC API.
First download the MySQL connector jar from www.mysql.com, then:
Right Click the project -- > build path -- > configure build path
In the libraries tab press Add External Jar and select your jar.
For Maven based projects you need a dependency.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
The driver connector is not in your build path. Configure the build path and point it to the 'mysql-connector-java-5.1.25-bin.jar' (check the version which you are using). Alternatively you can use maven :D
In the project into the folder Libraries-->right click --> Add Library --> Mysqlconnector 5.1
For IntelliJ Idea, go to your project structure (File, Project Structure), and add the mysql connector .jar file to your global library. Once there, right click on it and chose 'Add to Modules'. Hit Apply / OK and you should be good to go.
This needs to be used as of 2021
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
Trivial as it may seem in my case netbeans version maven project 7.2.1 was different. There is a folder in the project called dependencies. Right click and then it brings up a popup window where you can search for packages. In the query area put
mysql-connector
It will bring up the matches (it seems it does this against some repository). Double click then install.
It is because the WEB-INF folder does not exist at the location in the sub directory in the error. You either compile the application to use the WEB-INF folder under public_html OR copy the WEB-INF folder in sub folder as in the error above.
The exception can also occur because of the class path not being defined.
After hours of research and literally going through hundreds of pages, the problem was that the class path of the library was not defined.
Set the class path as follows in your windows machine
set classpath=path\to\your\jdbc\jar\file;.
I Understood your problem add this dependency in your pom.xml your problem will be solved,
https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.38
If you are using tomcat then along with project directory you should also copy the database connector jar file to tomcat/lib. this worked for me
I'm developing a simple JavaFX11 application with SQLite Database in Eclipse IDE. To generate report I added Jasper jars. Suddenly it throws "THIS" error.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
It was running good (BEFORE THIS ADDITION). But suddenly!
I'm not using maven or other managers for this simple application. I'm adding jars manually.
I created "User Library" and added my jars from external folders.
PROBLEM OCCURING AREA:
My "User Library" are marked as system library. I just removed the marking. Now its not a system library. "NOW MY PROJECT WORKING GOOD".
DEBUG MYSELF: Tried other things:
AT RUN CONFIGURATION: Try, removing library and add jars one-by-one and see. - here you have to delete all jars one by one, there is no select all and remove in eclipse right now in run configuration. So the error messages changes form one jars to another.
Hope this helps someone.
I was also facing the same problem
Download mysql-connector-java jar file
paste it in the C:\Program Files\Apache Software Foundation\Tomcat 9.0\lib
Hope this work for you also !!
Finally
I solved by two steps :
1 - add the below to pom.xml
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.8</version>
</dependency>
2 - Download jar file from this URL:https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.0.8
after that put it in your tomcat/lib folder.
I was having the same issue. I was using intellijj IDE for creating the MySQL connection.
Steps to fix it:
Download: mysql-connector.jar( I used 8.0.29).
Go to "file-->project structure -->Libraries-->Click on plus button and select java and select the jar file you downloaded in step 1".
Check the jar file is showing under "External Libraries directory"
4. Now try to create the connection. It will work.
I used this code for creating MySQL connection:
void createConnection() throws SQLException, ClassNotFoundException {
Connection connection=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/candelete"
,"root","");
System.out.println("Connection created");
System.out.println("hashcode is: "+connection.hashCode());
}
finally {
System.out.println("here");
System.out.println("hashcode is: "+connection.hashCode());
connection.close();
System.out.println("hashcode now: "+connection.hashCode());
}
}

OpenShift webapps mysql java connection

I have a JBoss EWS Tomcat 7 Java application on openshift, installed with the MySQL 5.5 and PhpMyAdmin 4.0 cartridges. I have copied the repository locally, and deleted the source folder. Instead, I simply have a compiled Java application, a WAR file, that has been copied into the webapps directory and git pushed to the OpenShift servers.
If I have some database, how would I be able to access it in the webapp compiled war file. Would standard MySQL JDBC work? According to some posts I have read, OpenShift blocks the accessing of external requests to the database, and in this case, the webapp directory's war file may be making an "external request". The source for that is here: https://www.openshift.com/forums/express/external-access-to-mysql (as answered by reputable OpenShift developers).
I actually tried JDBC in the past and it did not work, but that may have been due to incorrect code. If someone wants to write some code that shows how this would be done, I would appreciate it. And if you could test it that would be even nicer :)
By the way, in the answer please do not include port forwarding. I know that works, I have tried it before, and port forwarding works. But it is often a little insecure, and has to be started each time from a computer.
I have resolved the issue by myself and was extremely excited. Although I did not receive help myself, I hope someone else comes along this thread and is able to get it working!
So I have a Vaadin application, which has been compiled into a WAR file. I deployed it to OpenShift servers by the following steps:
Deployment of compiled webapp to OpenShift
Open OpenShift in your web browser. Log in to Openshift. Navigate to the application in question.
Get the ssh code of that application (it should be right of screen), located to the right of the cartridges. Copy that code using Command-C or Ctrl-C.
Open Terminal and type git clone ssh:\\xxxxxxxxxxxxxxxx...
If you are on Mac, like I am, it should create a project directory at Users/Username/Appname. Inside that directory, delete the source folder and pom.xml. Take your compiled WAR file and copy it into the webapps directory .
Go to Terminal. Type cd Appname, and then git add ., git commit -m "Deployment", and finally git push.
Your application should now fully function at www.openshiftappname-domainname.rhcloud.com/warfilename
MySQL access
Install the cartridges for MySQL and phpMyAdmin. This should be available through Add Cartidge at your openshift.com app hub.
Note your username and password to the MySQL database that OpenShift automatically generates for you. Go to www.openshiftappname-domainname.rhcloud.com/phpmyadmin, enter the authentication credentials.
Inside phpMyAdmin there should be the server IP address; it looks something like 127.x.y.z:3306. x, y, and z can be single digit to three digit numbers.
Quickly create a new database named whatever you want. I am going to name it test and then consequently produce a new table in there named testtable.
So remember your deployed WAR application? Well, if you are using MySQL, I bet you have already included it in your application. The basic steps to establish a connection to MySQL is as such.
Java Code
Go the open IDE project that you compiled into your WAR file. Go to the pom.xml inside your project if it is a Maven project, and add the dependency:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
Then use the following code.
String s = "jdbc:mysql://" + host + ":" + port + "/" + name", where host is the server IP address, the port is 3306 and name is the database name, in my case, test.
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Connection con = DriverManager.getConnection(s, username, password);
}
catch (SQLException e) {
e.printStackTrace();
}
Now if (con == null) it did not work. And if it is not null, it did.
To test, you should recompile your WAR file (after putting some way to visually test it). If you need further help, please leave a comment. It should work when you compile WAR file and redo steps 4-6 in the first section: Deployment of compiled webapp to OpenShift. Thanks!
Try checking out this KB about using the default mysql/postgresql connections that are available when using the java server cartridges on OpenShift: https://help.openshift.com/hc/en-us/articles/202399720-How-to-use-the-pre-configured-MySQLDS-and-PostgreSQLDS-data-sources-in-the-Java-cartridges

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
I'm getting the exception java.lang.ClassNotFoundException when I am trying to run my code,
My Code
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/simple",
"root","root");
Statement stmt=con.createStatement();
String query="SELECT * FROM CUST";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
System.out.print(rs.getString("CUST_NAME") +" ");
System.out.print(rs.getString(2) +" ");
System.out.print(rs.getString(3) +" ");
}
rs.close();
stmt.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
I'm getting Error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at Simple.MyProg.main(MyProg.java:15)
What am I doing wrong?
problem is not in the code, but you don't have added the driver to your project!!!
You have to add the *.jar driver to your project...
Try putting this in your lib directory, then re-starting tomcat...
problem is Class.forName("com.mysql.jdbc.Driver");
it tries to load the driver, but it is not getting it, this is the reason you are getting:
java.lang.ClassNotFoundException.
Copyed the *.jar into my WEB-INF/lib folder -> Worked for me. When including over buildpath there was everytime this errormsg.
The Problem is related to MySql Driver
Class.forName("com.mysql.jdbc.Driver");
Add the MySQL jdbc driver jar file in to your classpath.
Also i have this error on JDK. I build the ClassPath Properly then I put the "mysql-connector-java-5.1.25-bin" in dir "C:\Program Files\Java\jre7\lib\ext" in this dir i have my JDK. then compile and Run again then it's working fine.
You can download the latest mysql driver jar from below path, and copy to your classpath or if you are using web server then copy to tomcat/lib or war/web-inf/lib folder.
http://dev.mysql.com/downloads/connector/j/
or
http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/5.1.10/mysql-connector-java-5.1.10.jar
If you get this error when you are running it, then probably its because you have not included mysql-connector JAR file to your webserver's lib folder.
Now it is important to add mysql-connector-java-5.1.25-bin.jar to your classpath and also to your webserver's lib directory. Tomcat lib path is given as an example Tomcat 6.0\lib
Include path of jar (jdbc driver) in classpath.
if it is standalone program, download mysql connector jar and add it to your classpath.
if it is a maven project, add below dependency and run your program.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
Note that the name of the Driver class in mySQL v8 jar (at time of writing mysql-connector-java-8.0.12.jar) has changed to com.mysql.cj.jdbc.Driver
You can verify this for yourself by going into the jdbc jar and looking at the META-INF/services/java.sql.Driver file.
If you are using an eclipse ide, download the mysql jdbc connector jar and point that jar to the build path. Project Java Build Path --> Libraries --> Add external jars.
Connector can be obtained from http://dev.mysql.com/downloads/connector/j/
I had
runtime('mysql:mysql-connector-java')
Changed to
compile('mysql:mysql-connector-java')
Fixed my problem

java.lang.ClassNotFoundException: net.sourceforge.jtds.jdbc.Driver

I got this exception:
java.lang.ClassNotFoundException: net.sourceforge.jtds.jdbc.Driver
I use jtds-1.2.2. I tried add jar or add external jar.
I also do:
String driver = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I did the same in java project and everything works good.
But doing this in jsf project I get this exception. Why ?
The libraries used by a web application at runtime are all the jars placed in the WEB-INF/lib directory of the deployed webapp. Adding the library in the classpath used to compile the webapp doesn't make it automatically available at runtime.
If you're using Eclipse, just drop the jar in WebContent/WEB-INF/lib, and it will be automatically added to the build path (i.e. the classpath used to compile the app), and also be part of the deployed webapp, and thus be available at runtime.

Cannot connect to a mysql database with JSP, Glassfish

I have previous JSP experience but with using Tomcat and Resin and I would like to connect to a mySQL database using Glassfish and hoped that more or less copy and pasting the code would work.
The code is:
try {
Class.forName("org.gjt.mm.mysql.Driver");
} catch (Exception E) {
System.out.println("First: " + E);
}
Connection conn = DriverManager.getConnection("jdbc:mysql://xxx.xx.xx.xx:xxxx/DBName", "Username", "Password");
The errors I get when I look into my server logs are
[#|2012-03-09T13:50:21.900+0000|INFO|glassfish3.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=67;_ThreadName=Thread-1;|First:
java.lang.ClassNotFoundException: org.gjt.mm.mysql.Driver|#]
[#|2012-03-09T13:50:22.009+0000|INFO|glassfish3.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=67;_ThreadName=Thread-1;|java.sql.SQLException:
No suitable driver found for
jdbc:mysql://xxx.xx.xx.xx.xx/SmarterStudents|#]
I have put the mysql-connector-java-5.0.7-bin.jar into the domain/lib folder and threw it into the WEB-INF/lib folder just to be safe and it still wouldn't work for me.
I'm at my wit's end now, I just don't know what to do. D:
You're using the old and deprecated driver class name for the very first releases of the MySQL JDBC driver org.gjt.mm.mysql.Driver when it was still a hobby project, while you're using one of the more recent releases of the MySQL JDBC driver which has the driver class name com.mysql.jdbc.Driver.
Fix the classname accordingly.
Class.forName("com.mysql.jdbc.Driver");
Make sure that you're reading the official MySQL JDBC driver documentation instead of some random and heavily outdated resource/book/tutorial.
As to the placement of the JAR file, when you're managing the connections yourself in your web application, the JAR can be placed in both server's own /lib or webapp's /WEB-INF/lib. But when you're letting the server manage the connections (which will usually use a shared connection pool which is way much faster), then the JAR must be placed in server's own /lib folder. The one in the deployed webapp(s) will be ignored anyway.
Try working with JdbcOdbcDriver , but generally they say it should be used as a last resort.
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:db","root","root");
}catch(Exception e){
e.printStackTrace();
}
This should work for MySQL database, you need to install the connector for this as well, and the username and password generally for MySQL is root and root, respectively.

Categories