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());
}
}
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.
I was recently asked to troubleshoot an issue with a Spring Boot program that gets executed by Oozie. Unfortunately, I don't have access to the Spring Boot application or the logs. :) I do have the output from mvn dependency:tree -Ddetail=true
I'm told that the Spring Boot application runs fine on its own but won't run when executed as an Oozie Java action. We suspect that some of the dependencies that are added to the classpath by Oozie conflict with dependencies from Spring Boot.
This is somewhat speculative, but I'd like to run a simple Oozie Java action that captures the group, artifact, and version for all the dependencies that are added to the classpath and compare that to the dependency tree from the Spring Boot application. I'm thinking that, if there are version conflicts, it might be possible to exclude/resolve them in the pom.xml.
I wrote a class that writes the names of the jars in the classpath to a text file:
void captureClasspath(){
PrintWriter out = null;
try {
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
out = new PrintWriter(new OutputStreamWriter(
new BufferedOutputStream(new FileOutputStream("/tmp/classpath_capture.txt")), "UTF-8"));
for (URL url : urls){
out.println(url.getFile());
}
} catch (UnsupportedEncodingException | FileNotFoundException e) {
e.printStackTrace();
} finally {
if(out != null) {
out.flush();
out.close();
}
}
}
The output looks like this:
/hadoop/yarn/local/filecache/10/mapreduce.tar.gz/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-client-jobclient-2.7.1.2.4.3.0-227-tests.jar
/hadoop/yarn/local/filecache/10/mapreduce.tar.gz/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.1.2.4.3.0-227.jar
/hadoop/yarn/local/filecache/10/mapreduce.tar.gz/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-client-core-2.7.1.2.4.3.0-227.jar
/hadoop/yarn/local/filecache/10/mapreduce.tar.gz/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-client-hs-2.7.1.2.4.3.0-227.jar
/hadoop/yarn/local/filecache/10/mapreduce.tar.gz/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-client-jobclient-2.7.1.2.4.3.0-227.jar
... etc ... (more than 300 lines)
Instead of the filename, I'd like to extract the group, artifact and version from these jars. Is that possible? Or is there a better strategy to troubleshoot/resolve this issue given the limited input (no application logs, code, etc...)?
Instead of the filename, I'd like to extract the group, artifact and
version from these jars. Is that possible?
This would require reading the contents of each jar file and pulling the group, artifact and version from the relevant entry within the jar file. Some of the relevant methods for implementing this are JarFile#entries(), JarFile#getEntry(String) and JarFile#getInputStream(ZipEntry).
Maven builds will store an entry in the jar at META-INF/maven/<group>/<artifact>/pom.properties. For example, running jar xf hadoop-common.jar extracts META-INF/maven/org.apache.hadoop/hadoop-common/pom.properties, which contains the following data:
#Generated by Maven
#Thu Aug 18 01:41:25 UTC 2016
version=2.7.3
groupId=org.apache.hadoop
artifactId=hadoop-common
Several common sources of classpath version conflicts for Hadoop applications are Guava, Jackson and Protobuf.
I have been trying to deploy JAX-WS services on Weblogic server as demonstrated in this link, Creating a Simple HelloWorld Web Service.
I have deployed this and found to be working perfectly fine.
Now I also want to write data to log files, whenever this service is invoked. For this I'm using log4j. This is how i tried modifying the code in the link.
package examples.webservices.hello_world;
import javax.jws.WebService;
import org.apache.log4j.Logger;
#WebService(name="HelloWorldPortType", serviceName="HelloWorldService")
public class HelloWorldImpl {
public static Logger log = Logger.getLogger(HelloWorldImpl.class);
public String sayHelloWorld(String message) {
try {
log.info("Start");
System.out.println("sayHelloWorld:" + message);
} catch (Exception ex) { ex.printStackTrace(); }
return "Here is the message: '" + message + "'";
}
}
I have set the path of log4j-1.2.8.jar file in CLASSPATH variable.
But when i try to build the web service, it errs out saying, java.lang.ClassNotFoundException: org.apache.log4j.Logger.
I'm using the same build.xml file as given in the link. Are any modifications required in build.xml file? Where should i place the log4j.properties file? Any help is appreciated.
Even if your classpath is set, this issue has to be because weblogic is not able to find log4j at runtime. To be more specific, the Classloader of the war is not able to find the log4j.
Here are the ways to troubleshoot:
Check your build.xml if you are infact bundling log4j in your WAR.
Go to the autodeploy directory, copy the war file to a different location, deflate it and check if WEB-INF/lib and check if log4j indeed exists
Check if there is more than one log4j version in your classpath.
Finally, the preferred approach for deploying set of reusable jars in weblogic is by a shared library and reference it through weblogic.xml.
It helps in:
Avoiding repetitive bundling of a jar file in different wars.
Making sure that all your deployment are streamlined to a preferred version
of a library.
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