There is a VERY similar question to mine but in my case I don't have any duplicate jars in my build path, so the solution does not work for me. I've searched google for a couple of hours now, but none of the solutions I've found there actually resolve my issue. I'm creating a web site with some database connectivity for a homework. I'm using a MySQL database, developing in Eclipse and running on Windows.
I keep getting java.lang.ClassNotFoundException: com.mysql.jdbc.Driver with the following code:
import java.sql.*;
//...
public void someMethodInMyServlet(PrintWriter out)
{
Connection connection = null;
PreparedStatement query = null;
try {
out.println("Create the driver instance.<br>");
Class.forName("com.mysql.jdbc.Driver").newInstance();
out.println("Get the connection.<br>");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "secret");
query = connection.prepareStatement( "SELECT * FROM customers");
//...
} catch (Exception e)
{
out.println(e.toString()+"<br>");
}
}
//...
When I run the above code I get the following output:
Create the driver instance.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
It doesn't get past the Class.forName... line and I can't figure out why! Here is what I did:
Download mysql-connector.
Put it in my MySQL folder C:\Program Files\MySQL\mysql-connector-java-5.1.12\mysql-connector-java-5.1.12-bin.jar.
Opened the project properties in Eclipse.
Add External Jar to my Build Path and I selected mysql-connector-java-5.1.12-bin.jar.
Every time I attempt to use the servlet I get the same error regardless if I have the jar in there or if I don't. Could you help me figure this out?
As for every "3rd-party" library in flavor of a JAR file which is to be used by the webapp, just copy/drop the physical JAR file in webapp's /WEB-INF/lib. It will then be available in webapp's default classpath. Also, Eclipse is smart enough to notice that. No need to hassle with buildpath. However, make sure to remove all unnecessary references you added before, else it might collide.
An alternative is to install it in the server itself by dropping the physical JAR file in server's own /lib folder. This is required when you're using server-provided JDBC connection pool data source which in turn needs the MySQL JDBC driver.
See also:
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
How should I connect to JDBC database / datasource in a servlet based application?
Where do I have to place the JDBC driver for Tomcat's connection pool?
JDBC CLASSPATH Not Working
Since you are running it in servlet, you need to have the jar accessible by the servlet container. You either include the connector as part of your application war or put it as part of the servlet container's extended library and datasource management stuff, if it has one. The second part is totally depend on the container that you have.
The others are right about making the driver JAR available to your servlet container. My comment was meant to suggest that you verify from the command line whether the driver itself is intact.
Rather than an empty main(), try something like this, adapted from the included documentation:
public class LoadDriver {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
}
}
On my platform, I'd do this:
$ ls mysql-connector-java-5.1.12-bin.jar
mysql-connector-java-5.1.12-bin.jar
$ javac LoadDriver.java
$ java -cp mysql-connector-java-5.1.12-bin.jar:. LoadDriver
On your platform, you need to use ; as the path separator, as discussed here and here.
Place mysql-connector-java-5.1.6-bin.jar to the \Apache Tomcat 6.0.18\lib folder. Your problem will be solved.
What you should not do do (especially when working on a shared project)
Ok, after had the same issue and after reading some answers here and other places. it seems that putting external lib into WEB-INF/lib is not that good idea as it pollute webapp/JRE libs with server-specific libraries - for more information check this answer"
Another solution that i do NOT recommend is: to copy it into tomcat/lib folder. although this may work, it will be hard to manage dependency for a shared(git for example) project.
Good solution 1
Create vendor folder. put there all your external lib. then, map this folder as dependency to your project. in eclipse you need to
add your folder to the build path
Project Properties -> Java build path
Libraries -> add external lib or any other solution to add your files/folder
add your build path to deployment Assembly (reference)
Project Properties -> Deployment Assembly
Add -> Java Build Path Entries
You should now see the list of libraries on your build path that you can specify for inclusion into your finished WAR.
Select the ones you want and hit Finish.
Good solution 2
Use maven (or any alternative) to manage project dependency
Just follow these steps:
1) Install eclipse
2) Import Apache to eclipse
3) Install mysql
4) Download mysqlconnector/J
5) Unzip the zipped file navigate through it until you get the bin file in it. Then place all files that are present in the folder containing bin to C:\Program Files\mysql\mysql server5.1/
then give the same path as the address while defining the driver in eclipse.
That's all very easy guys.
If the problem still persists,
Put the-
mysql-connector-java-5.0.8-bin jar in a place inside your Tomcat->lib->folder (No matter where you've installed your Tomcat). And change your environmental variable (Done by clicking Properties of Mycomputer -Advanced system settings- Environmental variables-And set a new variable name & variable values as the place where your lib file resides.Dont forget to enter a ; at the end of the path)
If still problem persists
Try downloading commons-collections-2.0.jar (http://www.docjar.com/jar_detail/commons-collections-2.0.jar.html) and paste the jar in the same place where your mysql jar resides (ie) inside Tomcat-lib.
Clean your project-Stop your server- Finally try to run.
Many times I have been facing this problem, I have experienced ClassNotFoundException.
if jar is not at physical location.
So make sure .jar file(mysql connector) in the physical location of WEB-INF lib folder. and
make sure restarting Tomcat by using shutdown command in cmd.
it should work.
The only solution worked for me is putting the .jar file under WEB-INF/lib . Hope this will help.
assuming your project is maven based, add it to your POM:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
Save > Build > and test connection again. It works! Your actual mysql java connector version may vary.
Put mysql-connector-java-5.1.38-bin.jar to the C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib folder.by doing this program with execute
My issue was a little different. Instead of jdbc:oracle:thin:#server:port/service i had it as server:port/service.
Missing was jdbc:oracle:thin:# in url attribute in GlobalNamingResources.Resource. But I overlooked tomcat exception's
java.sql.SQLException: Cannot create JDBC driver of class 'oracle.jdbc.driver.OracleDriver' for connect URL 'server:port/service'
for this error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
you need to:
Import java.sql.*;
Import com.mysql.jdbc.Driver;
even if its not used till app running.
Related
I've been working with a Java program which performs several queries against an Oracle database. I'm currently using the jdbc thin client (ojdbc7.jar) for this. For an IDE I'm using NetBeans, and debugging or running the JAR on my PC I've faced no Errors. Running this JAR on a Linux environment for production however, the following error is reported:
Exception in thread "main" java.lang.NoClassDefFoundError: oracle/jdbc/OracleDriver
[...]
Caused by: java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver
The code I'm using to get the connection is:
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", DBUsername);
connectionProps.put("password", DBPassword);
conn = DriverManager.getConnection(JDBCConnection, DBUsername, DBPassword);
With DBUsername/Password and JDBCConnection all being locally stored. Adding additional print statements shows the failing line is:
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
I currently have ojdbc7.jar included under Libraries in my project. Checking the project properties under Build > Packaging, "Copy Dependent Libraries" is checked. My expectation at this point is the library should be included in my jar file.
I have also tested:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Similarly, I've tried using only Class.forName(), and using both.
Class.forName("oracle.jdbc.driver.OracleDriver");
Reading other questions, I understand this could be an issue with my classpath. In the Linux environment I'm trying to run this in, I set the classpath to the exact location of the ocjdb7.jar without luck:
export CLASSPATH=/<Directory Location>/ocjdb7.jar
I've tried multiple configurations of this, for example the Linux environment in question already had a classpath including ocjdb6.jar, so I recompiled with this version, set the classpath, and tested. Same error message reported. Have I missed a necessary setup to include this driver? Testing on a coworkers Windows 7 desktop, the same error occurred which seems to indicate this is still a setup issue.
The answer was simple - Netbeans includes any referenced libraries in a lib folder under the dist folder it compiles the JAR files to. I had been copying only the compiled JAR, but not the associated lib folder. After copying the lib folder, the process ran without exceptions.
Netbeans documentation covers how this functions, which states:
https://netbeans.org/kb/articles/javase-deploy.html
If you have specified any libraries for the project (in addition to the JDK), a lib folder is created in the dist folder. The libraries are copied into dist/lib.
The ocjdb7.jar should be packaged into your executable JAR. I suggest you try to make a maven project out of it (NetBeans should have a convenient wizard for that) and reference it as a dependency.
You can also check, if the required ocjdb7.jar was packaged into your JAR when you extract it (a JAR is just an archive file).
I have created a Java application that uses a database, and I now want to build it into a jar file and make it so that the database works without NetBeans. I thought NetBeans would automatically include the database, but it doesn't.
The files that NetBeans include in the 'dist' folder when I build it look like this:
dist
lib
derby.jar (Executable Jar File)
derbyclient.jar (Executable Jar File)
README
WordFinder.jar (Executable Jar File)
Everything except the database-related code works when I launch the WordFinder.jar file after closing NetBeans.
I noticed that the database is using 'org.apache.derby.jdbc.ClientDriver', and I'm wondering, does that need to be 'org.apache.derby.jdbc.EmbeddedDriver' in order for it to include the database?
Are there any files that I need to include? I'm new to Java databases, so try to keep the instructions simple.
You need to start the database server in you computer, for doing that you need to go to your derby path (C:\Program Files\Java\jdk1.8.0_45\db\bin) and run the startNetworkServer.bat file
I may be a year late but seeing the comments, I'm assuming the issue hasn't been resolved yet. I had the same problem and would like to show how I worked around it. Note I'm not using an embedded derby database.
1) I changed my connection string. Instead of the usual "jdbc:derby://localhost:1527/myDB;create=true;...." , I put the exact location of the database which can be found usually under C:\Users\myPC\.netbeans-derby\myDB
2) Clean and build the project which should give you the "dist" folder which would include the jar file of the project together with the "lib" folder.
3) Start the StartNetworkServer.bat which is located in the bin folder under derby folder. A cmd would show that will say something "Apache Derby Network Server blah blah blah started and ready to accept connections on port 1527"
4) After doing those, run the jar file and it should run even with the netbeans IDE closed.
That's about it. That's how I got mine to work without opening Netbeans IDE. Hope it helps.
I have been following this tutorial accordingly.
Up to running the FirstExample class in the command prompt is when it starts to freak out for some reason. After attempting to run the following command:
java FirstExample
I get the following exception:
Exception in thread "main" java.lang.NoClassDefFoundError: FirstExample
I understand that it can't find the FirstExample class due to the classpath (for some reason) so I executed the following command:
java -cp . FirstExample
And now it returns a new exception:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Now it can't find the JDBC Driver. This confuses me because for starters, I ran the exact same coding through Eclipse and it works as expected, and secondly, I went as far as to ensure that I execute the same class file that Eclipse is executing, and the command prompt still returns exceptions. I also went as far as to put the FirstExample file in a separate folder, just for the purpose of copying and pasting the MySQL Connector into the same folder, and I still get exceptions.
I just don't understand whats going on, can someone help me please?
Many thanks.
The file path to the connector is as followed:
C:\Program Files\MySQL\mysql-connector-java-3.1.14\mysql-connector-java-3.1.14-bin.jar
Hope this helps.
For testing purposes, I have placed the FirstExample class under the following path:
C:\java
This confuses me because for starters, I ran the exact same coding through Eclipse and it works as expected
This is because in Eclipse you add the libraries to the Build Path, and it will use all the libraries specified there in the classpath automatically when running your project. This can be noted here:
In order for you to execute your project using third party libraries from command line tools, you should specify the libraries manually in your classpath explicitly:
java -cp <path/to/mysql_jar/goes/here>:. FirstExample
By your comment:
the path to the MySQL file is: C:\Program Files\MySQL\mysql-connector-java-3.1.14\mysql-connector-java-3.1.14-bin.jar (...) I have placed the FirstExample class under C:\java
This should be the command line to use:
java -cp "C:\Program Files\MySQL\mysql-connector-java-3.1.14\mysql-connector-java-3.1.14-bin.jar; ." FirstExample
Note that it is better to store all the third party libraries in a single folder within your project, usually called lib, and put a reference to there. Assuming your current folder has a lib folder and all the third party libraries are copied there, the command line would be:
java -cp "lib\*; ." FirstExample
Use the next example to add your jars to the classpath:
java -cp "jdbc.jar;lib/*" my.package.FirstExample
You need to have the class com.mysql.jdbc.Driver (and all the imported classes) in the classpath too.
You should download the jar (http://dev.mysql.com/downloads/connector/j/5.0.html) and add it to the classpath.
The ClassNotFound Exception rises when there is an issue with the class name that you have written in Class.forName() or if the package is not set to the classpath variable. Make sure that you have added the jar file to the classpath ( C:............\jarfilename.jar;).
This is applicable for any JDBC Driver and jar files. The .jar files that are added to the classpath will not be visible to IDEs, in this case, you need to add the jar files to buildpath (in eclipse) or you can also copy the jar files to ext folder available in the Java installation folder.
Also note that the jar files of the DB Softwares may vary based on the DB software version that you are using for example if you are using the Oracle 11g, you need ojdbc6.jar file, in other versions of Oracle the number changes like ojdbc14.jar etc.
I am fairly new to Linux, I am trying to set my jar files for OJDBC in my classpath but so far have not found any good examples for a beginner such as me.
I will list the my paths for Jar file below. Can someone provide me with example or how to step by step set my class path with the commands. I would really appreciate it. I would like to set this path in my project which I am using it in.
Jar file:
/home/ssingh/Downloads/oracle.jar
Project:
/opt/savi/Workspace/SgRecc/bin/PerVal.class
Setting up the Class Path
To use the driver, the JAR archive named postgresql.jar if you built from source, otherwise it will likely be (named with the following convention: postgresql-[server version].*[build number].jdbc[JDBC version]*.jar, for example postgresql-8.0-310.jdbc3.jar) needs to be included in the class path, either by putting it in the CLASSPATH environment variable, or by using flags on the java command line.
For instance, assume we have an application that uses the JDBC driver to access a database, and that application is installed as /usr/local/lib/myapp.jar. The PostgreSQLâ„¢ JDBC driver installed as /usr/local/pgsql/share/java/postgresql.jar. To run the application, we would use:
export CLASSPATH=/usr/local/lib/myapp.jar:/usr/local/pgsql/share/java/postgresql.jar:.
java MyApp
In Tomcat I want to use a jar inside a web application. The jar file will exist outside of the Tomcat directory.
To include the jar file in tomcat classpath, I modified the TomcatHome/conf/catalina.properties to include the absolute path of my jar file like,
shared.loader=D:\jaa\MyJarFile.jar
as per the suggestion given in link,
http://www.mulesoft.com/tomcat-classpath
But it throws the error,
java.lang.NoClassDefFoundError
I have also tried ,
shared.loader=D:\jaa\*.jar
shared.loader=file:\\D:\jaa\MyJarFile.jar
None of them seem to work :(
If I try placing the jar inside tomcat/lib it seem to work. But I am not allowed to do that.
Please help me out with this issue as I have implementation the next week..
I figured myself how to add the classpath for tomcat. Instead of editing catalina.properties, just create a "setenv.sh" in the Tomcat Bin directory with the classpath,
Example,
CLASSPATH=D:\jaa\MyJarFile.jar
I just checked the catalina.sh in Tomcat/bin and these classpath variable will be set while setting the bootstrap as the classpath.
I was using IntelliJ and I tried everything like:
Using CtrlAltShiftS (Project Settings) and adding a dependency of mysql-connector.jar. Didn't work. (The only thing that worked was that code completion inside IntelliJ was working fine.
Adding mysql-connector.jar to apache-home/lib/ folder. Didn't work.
Including mysql-connector.jar from Maven inside IntelliJ. Just didn't work.
The thing that worked for me:
Include the mysql-connector.jar file in the PROJECT/web/WEB-INF/lib folder.
No need to add it as a dependency anywhere. Just compile this and it will work fine.
I find myself copying extra JARs, which should be available for all contexts and should therefor go into the root loader, into the following directory:
C:\Program Files\Apache Software Foundation\Tomcat 9.0\lib
But this only possible if you have access to this directory, which might not be the case for all ISPs. At least you can do it at home.
Bye