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 have a java code snippet
TitanGraph g = TitanFactory.open("titan-all-0.4.4/conf/titan-berkeleydb.properties");
where titan-berkeleydb.properties is the in build config file that comes with Titan db installation.
On execution, it throws an exception
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.commons.lang.StringUtils.isNotBlank(Ljava/lang/String;)Z
at com.thinkaurelius.titan.graphdb.configuration.KCVSConfiguration.<init>(KCVSConfiguration.java:40)
at com.thinkaurelius.titan.diskstorage.Backend.initialize(Backend.java:273)
at com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration.getBackend(GraphDatabaseConfiguration.java:1174)
at com.thinkaurelius.titan.graphdb.database.StandardTitanGraph.<init>(StandardTitanGraph.java:75)
at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:40)
at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:29)
Is there a way to resolve this issue?
Check your classpath for another commons-lang-*.jar. According to the Apache Commons documentation, the isBlank() method is new since 2.0.
https://commons.apache.org/proper/commons-lang/javadocs/api-2.5/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29
Titan 0.4.4 ships with commons-lang-2.5.jar in the lib directory. Your original post didn't mention anything else about the runtime environment. I would suspect that if you had, for example, commons-lang-1.0.1.jar on the classpath, it would be picked up before commons-lang-2.5.jar and you would see the error.
If you're using a web application with Tomcat, you have to add the jar file into WEB-INF/lib folder of the application (or into $TOMCAT_HOME/lib folder, if you have more webapps using it).
Either create a library with this jar and add it to the project class path.
If you done all this and it still not working, you can change the jar extension to zip or rar and open it to see if the requested classes you need are inside.
I am getting an exception:
Cannot find symbol: FileUploadException;
I have a piece of code which uses
FileUploadException
The library that needs importing is:
org.apache.commons.fileupload.FileUploadException
The path to my project is :
D:\Projects\website
In the project folder I have each in its folder:
Tomcat, Derby, Website
I have copied:
commons-fileupload.jar and commons-io.jar
into both:
Tomcat/lib and Website/Web-INF/lib
---------------I tried this--------------
just importing the library on its own
import org.apache.commons.fileupload.FileUploadException;
adding the jars to the class path upon build:
javac -cp .;D:Projects\website\Tomcat\lib\commons-fileupload.jar;D:\Projects\website\Tomcat\lib\commons-io.jar com/otrocol/app/*.java
adding them to the Environment variables CLASSPATH
D:Projects\website\Tomcat\lib\commons-fileupload.jar;D:\Projects\website\Tomcat\lib\commons-io.jar
I also tried adding the jars where my .java files are as #Scot Ship suggested
----mentions---
I am not using any IDE
The code contains more unrecognized symbols, but I'm trying to solve one at a time
First time using apache, tomcat, jsp.. please be gentle
Vlad, the web container will automatically look for JARs inside
/WEB-INF/lib
even without any developer intervention. Take note that it's all caps WEB-INF. As long as your JAR is there, it will be in your web application's classpath.
Try to display this in one of your servlets or JSP:
System.getProperty("java.class.path")
and you'll get a better view of what classes and JARs were actually loaded.
Update: After reviewing your question, it appears you're facing issues in compiling the files to begin with and you're doing it outside an IDE.
Take note that when you use -cp in javac like this:
javac -cp .;D:Projects\website\Tomcat\lib\commons-fileupload.jar;D:\Projects\website\Tomcat\lib\commons-io.jar com/otrocol/app/*.java
Whatever value you have set in the CLASSPATH environment variable becomes ignored.
Be absolutely sure that the class FileUploadException is indeed inside one of the JARs you're trying to import: you can view the JAR directly using an unarchiving tool.
Also, change the com/otrocol/app/*.java to com\otrocol\app*.java - you should be using your system delimiter (not that this may affect your problem).
Create a simple HelloWorld in the same location as the file you're compiling, add the SystemOut mentioned above, and compile it the same way you're doing for the concerned file.
Read this http://commons.apache.org/proper/commons-fileupload/faq.html#class-not-found. Probably you have the fileupload jar but you also need commons-io.jar in your classpath as well.
I am using JAVA (with eclipse juno) and try to create an executable JAR file which include sqlite DB file.
I've try to get connection to the DB by this line:
DriverManager.getConnection("jdbc:sqlite:"+DataController.class.getResource("test.sqlite").getPath())
The DataController is a class that located where the sqlite located.
and i keep get an error:
java.sql.SQLException: invalid database address
Does someone can help and give step by step instructions about how to include sqlite DB inside an executable JAR file?
Apparently sqlite-jdbc can open resources on it's own. Per this thread https://groups.google.com/forum/?fromgroups=#!topic/xerial/Oayzj5nrJGk, add :resource to the path. So try the following:
DriverManager.getConnection("jdbc:sqlite::resource:package/test.sqlite");
or depends on version of sqlite
DriverManager.getConnection("jdbc:sqlite::resource:package/test.db");
Replacing package with the '/' separated path to the package this file is in.
Be aware that it will actually copy the file to a tmp directory.-
The ::resource way is right. And these explanations will help if you are using ::resource but still get errors like resource database.db not found: java.net.MalformedURLException: no protocol: database.db like verdana.
Most common anwsers are:
DriverManager.getConnection("jdbc:sqlite::resource:path/to/database.db")
However the path/to/database.db must be the exact path(the Path in Real File System but not in Jar) to your jar file.
I recommend to use getClass().getResource():
DriverManager.getConnection("jdbc:sqlite::resource:" +
getClass().getResource("/path/to/db/in/the/jar/file"))
NOTE:the /path/to/db/in/the/jar/file part must start with /
I'm not sure if this has changed in recent JDBC versions, but after fiddling with it for about an hour and getting various exceptions (MalformedURLException and "Database has been closed"), I found that the following worked for me:
DriverManager.getConnection("jdbc:sqlite::resource:file:/path/to/database.db")
The :file: portion seems to be missing from other answers and I couldn't get it to work without it.
Also, note that the
/path/to/database.db
is the absolute path starting from the root of the .jar file, rather than a normal resource root.
jdbc:sqlite::resource:notes_app.db
worked for me. My database(notes_app.db) was in the root of generated jar file.
public class Database {
public static Connection con () throws SQLException {
String url = "jdbc:sqlite::resource:notes_app.db";
return DriverManager.getConnection(url);
}
}
My notes_app.db is in the root of generated jar. I'm developing with maven and notepadd++
I have a terrible problem with Tomcat, well terrible because of this problem I've thrown away the project for more than a month now... Yet I'll still need to solve it and to go on with the project...
So it's throwing me this error:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://isd.ktu.lt:1433;DatabaseName=LN2012_bakDB2
java.lang.NullPointerException
The thing is that the same application is working in the desktop version perfectlz, however when it comes to the version which is supposed to be running on the server (Tomcat 7.0.22.0 inside NetBeans 7.1.2) it just throws the Error. It seems it doesn't load the pooling driver or I don't even know...
Well here's the part responsible for that:
public DatabaseConnection(Parameters params) {
// parameters and the output
this.gui = params.getGui();
// activate database pool
connectionPool = new GenericObjectPool(null);
connectionFactory = new DriverManagerConnectionFactory(params.getDbAdr(), params.getDbUser(), params.getDbPass());
poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
driver = new PoolingDriver();
driver.registerPool("GenTreeDatabase", connectionPool);
//driver.registerPool("jdbc:apache:commons:dbcp:GenTreeDatabase", connectionPool);
}
public void openConn() {
if (allowOutput) gui.print("Getting connection to database");
try {
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:GenTreeDatabase");
if (con != null) {
if (allowOutput) gui.print("Connection to database was successful");
}
} catch (SQLException ex) {
gui.err(specificError + "Error getting connection to database - " + ex);
}
}
It happens at the point where it tries to get the connection, then it gets a null pointer exception, since the connection is not retrieved successfuly.
I'm not familiar with Tomcat and up until this moment, Netbeans handled tomcat fine...
The thing is I hate errors like this... If you don't solve it in three days, you get so frustrated and don't wanna get back to that, you feel like hitting a wall...
Now I tried googling a lot about it, but still it wasn't much of a help...
So I'd be really glad if somebody could help me with this. Thanks. :)
You have to copy the JDBC Driver's jar into $CATALINA_HOME/lib.
This is probably too late to answer this question but in order to help with similar issues, Here's how I got around it.
Quick Solution:
Copy the JDBC-driver JAR file (mine was ojdbc6) into $JAVA_HOME/jre/lib/ext (for me it was C:\Program Files\Java\jdk1.7.0_80\jre\lib\ext).
Details:
According to Apache Tomcat 7 documentations When Tomcat is started, it creates a set of class-loaders that are organized into the following parent-child relationships:
Bootstrap
|
System
|
Common
/ \
Webapp1 Webapp2 ...
Each class loader, searches for JAR files inside a certain directory. The classes and resources that they make visible are explained below:
Bootstrap : This class loader contains the basic runtime classes provided by the JVM, plus any classes from JAR files present in the System Extensions directory $JAVA_HOME/jre/lib/ext.
System : This class loader is normally initialized from the contents of the CLASSPATH environment variable. All such classes are visible to both Tomcat internal classes, and to web applications. However, There are some exceptions for Tomcat.
Common : This class loader contains additional classes that are made visible to both Tomcat internal classes and to all web applications. This class loader looks (by default) in $CATALINA_BASE/lib and $CATALINA_Home/lib for jar files.
Webapps : A class loader is created for each web application that is deployed in a single Tomcat instance. All unpacked classes and resources in the /WEB-INF/classes directory of your web application, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application, are made visible to this web application, but not to other ones.
In conclusion, buy putting the ojdbc JAR file inside $JAVA_HOME/jre/lib/ext the JDBC driver, will get visible at the Bootstrap level.
I too encountered the same issue. It is because your tomcat server does not have the jar file of your JDBC. I fixed the problem by copying the JAR file to lib folder in tomcat server.
it helped me copying the mssql-jdbc-9.2.1.jre8.jar file to the C: \ Java \ jdk1.8.0_291 \ jre \ lib \ ext folder
I'm attempting to export a jar file containing the ojdbc14.jar, to allow execution outside of my machine. I can do so successfully with the current export of my jar, but only on my computer, when others try it fails with the error: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver when it attempts to call Class.forName
I have seen many similar questions on SO concerning this, but none of the questions seem to have the exact problem, and the solutions aren't working either.
Class:
InputStream inputStream = JdbcConnection.class.getClassLoader().getResourceAsStream("properties/jdbc.properties");
try {
PROPERTIES.load(inputStream); //Load the jdbc properties
//System.out.println(properties.getProperty("jdbc.driverClassName")); <-- this prints out the correct output`
Class.forName(PROPERTIES.getProperty("jdbc.driverClassName")).newInstance(); //Load the oracle driver
Manifest: (my ojdbc14.jar is located in lib, but the jar will only work on my local machine if just "ojdbc14.jar" is included, the other jars don't have an issue with the path provided, not sure if that is important)
Manifest-Version: 1.0
Main-Class: JdbcConnection
Class-Path: lib/ojdbc14.jar ojdbc14.jar extrsrcs/kxml2-2.3.0.jar extrsrcs/xstream-1.4.2.jar src/properties/jdbc.properties
UPDATE:
This question better explains how I resolved my issue, as it was related to Jar-within-Jars, executable jars, and etc.
I didn't think you could include other jars within a jar (that is what your trying to do isn't it?)
I suspect it's working on your machine because ojdbc14.jar is on your classpath somewhere (ie. as the standalone file, rather than included in your jar)
Hope this helps
Nathan