mysql JDBC Connection NoClassDefFoundError - java

I am trying to test mySQL JDBC connection on a windows 2008 server. I have downloaded the JDBC driver and it created a jar file at "C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.34-bin.jar".
When I am running a small program to test my jdbc connection , I am getting "NoClassDefFound" error.
What am i missing here?
I did set up jdbc jar in classpath
C:\>echo %CLASSPATH%
C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.34-bin.jar;
I have placed the jar in same location where I have my DBDemo.java (C:\test)
DemoDB.java
import java.sql.*;
import java.util.Properties;
public class DBDemo
{
// The JDBC Connector Class.
private static final String dbClassName = "com.mysql.jdbc.Driver";
// Connection string. emotherearth is the database the program
// is connecting to. You can include user and password after this
// by adding (say) ?user=paulr&password=paulr. Not recommended!
private static final String CONNECTION =
"jdbc:mysql://127.0.0.1/emotherearth";
public static void main(String[] args) throws
ClassNotFoundException,SQLException
{
System.out.println(dbClassName);
// Class.forName(xxx) loads the jdbc classes and
// creates a drivermanager class factory
Class.forName(dbClassName);
// Properties for user and password. Here the user and password are both 'paulr'
Properties p = new Properties();
p.put("user","paulr");
p.put("password","paulr");
// Now try to connect
Connection c = DriverManager.getConnection(CONNECTION,p);
System.out.println("It works !");
c.close();
}
}
*Error *
C:\Program Files\Java\jdk1.6.0_45\bin>java c:\test\DBDemo
Exception in thread "main" java.lang.NoClassDefFoundError: c:\test\DBDemo
Caused by: java.lang.ClassNotFoundException: c:\test\DBDemo
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: c:\test\DBDemo. Program will exit.

C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.34-bin.jar;
Your CLASSPATH seems to be not having . that is the current working directory where the DBDemo would be there. So add . also to your CLASSPATH. After that your CLASSPATH will be like
.;C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.34-bin.jar;
EDIT
Also try extracting the contents of mysql-connector-java-5.1.34-bin.jar into a folder and change the CLASSPATH according to that.

Exception in thread "main" java.lang.NoClassDefFoundError
One of the places java tries to find your .class file is your current directory. So if your .class file is in c:\test\, you should change your current directory to that.
To change your directory, type the following command at the prompt and press Enter:
cd c:\test\
Also
set CLASSPATH = .;C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.34-bin.jar;C:\Program Files\Java\jdk1.6.0_45\lib\tools.jar;
set PATH = C:\Program Files\Java\jdk1.6.0_45\bin
Executing your program using this command should correct the problem:
c:\test>java DemoDB

This problem can have several causes, but one of the most common is that the classes or dependencies cannot see each other, you must verify the import of each class or dependency, if you have renamed packages, classes or dependencies then the JVM cannot find the class or dependency sought.

Related

JDBC Class can not be found during runtime [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
How to use a wildcard in the classpath to add multiple jars? [duplicate]
(4 answers)
Closed 3 years ago.
I am creating an application that is utilizing JDBC and am currently having problems running the code without getting java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver. I have done extensive research into trying to solve this issue and nothing i have tried seems to work.
For one, I would like to note that my code works fine when it is run from my IDE (intellij). The database connection works and all the queries execute as necessary. The problem comes when I try to compile and run using javac and java in the terminal. Becuase this is a school project, I will need to enable my professors to be able to run it locally.
Secondly, I am compiling the application using the same jar files that are also included within intellij:
javac -classpath lib/\* DatabaseDriver.java
The lib folder contains my JDBC jar file. You can find the two jar files in this folder here (json.org) and here (connector j). Everything compiles correctly but it seems that once the following execution occurs in the code (see below for the full code) the is a runtime excetion that says the class can not be found:
Class.forName("com.mysql.cj.jdbc.Driver"); // also tried com.mysql.jdbc.Driver
The following code is what I am trying to compile (not the full DatabaseDriver, just enough to reproduce the issue):
import org.json.JSONObject;
import java.sql.*;
public class DatabaseDriver {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
public static String runStatement(String sql) throws Exception {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
return "";
}//end main
public static void main(String[] args) throws Exception {
DatabaseDriver.runStatement("SELECT * FROM employees LIMIT 10");
}
}
This is the full stack that I get when I run the code:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at DatabaseDriver.runStatement(DatabaseDriver.java:15)
at DatabaseDriver.main(DatabaseDriver.java:40)
Problem Summary: I am unable to run this script such that the jar file gets picked up even though it is the same jar file that my IDE is able to properly use. There must be something that I am forgetting or missing to do because all of the solutions I am finding only have to deal with people forgetting to include the correct jar files.
Run your class as given below:
In Unix based systems
java -cp ".:lib/*" DatabaseDriver
In MS Windows
java -cp ".;lib/*" DatabaseDriver

Java RXTXcomm Lib does not load or is not to be found

I want to do a small test with a nanoCUL868 USB device in order to transmit some signal to remote devices. The stick works with some 3rd party software and I was able to communicate with the remote device. I now want to test this stick with the following code in JAVA:
package de.saltest.home;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Logger;
import org.openmuc.jrxtx.Parity;
import org.openmuc.jrxtx.SerialPort;
import org.openmuc.jrxtx.SerialPortBuilder;
public class SomfyCULTest {
private static final Logger log = Logger.getLogger(SomfyCULTest.class.getName());
public static void main(String[] args) throws IOException {
log.info("Opening port ttyUSB0");
SerialPort port = SerialPortBuilder.newBuilder("/dev/ttyAMA0").setBaudRate(9600).setParity(Parity.NONE).build();
OutputStream out = port.getOutputStream();
String commandLEDOn = "l01\n";
String commandLEDOff = "l00\n";
String encryptionKey = "A1";
// C - Command (1 = My, 2 = Up, 4 = Down, 8 = Prog)
String command = "2";
String rollingCode = "001D";
String address = "000029";
String somfyCommand = "Ys" + encryptionKey + command + "0" + rollingCode + address + "\n";
out.write(somfyCommand.getBytes());
out.close();
port.close();
log.info("Closed port");
}
}
I have installed Oracle Java on a Rasperry Pi 3 and also got the librtrx-java via apt-get. A dpkg-query -L librxtx-java yields:
/usr/lib/jni/librxtxRS485.so
/usr/lib/jni/librxtxRaw.so
/usr/lib/jni/librxtxI2C.so
/usr/lib/jni/librxtxParallel.so
/usr/lib/jni/librxtxSerial.so
/usr/share/java/RXTXcomm.jar
So, I assume those libraries are correctly installed for the right platform.
If I use javac to compile my code:
I get the following error message:
javac -classpath /usr/lib/jni -cp /usr/share/java/RXTXcomm.jar:. src/main/java/de/saltest/home/SomfyCULTest.java
src/main/java/de/saltest/home/SomfyCULTest.java:7: error: package org.openmuc.jrxtx does not exist
import org.openmuc.jrxtx.Parity;
^
I have also a maven project which compiles fine using this code, however, I cant execute it because of the following error:
mvn exec:java -Dexec.mainClass=de.saltest.home.SomfyCULTest
[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) # serialTest ---
Okt 07, 2018 3:25:41 PM de.saltest.home.SomfyCULTest main
INFORMATION: Opening port ttyUSB0
Could not load lib from jar and from system.
gnu.io.LibLoadException: directory does not exist /libs
at gnu.io.LibraryLoader.loadLib(LibraryLoader.java:65)
at gnu.io.LibraryLoader.loadLibsFromJar(LibraryLoader.java:48)
at gnu.io.LibraryLoader.loadRxtxNative(LibraryLoader.java:29)
at gnu.io.RXTXCommDriver.<clinit>(RXTXCommDriver.java:85)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at gnu.io.CommPortIdentifier.<clinit>(CommPortIdentifier.java:104)
at org.openmuc.jrxtx.JRxTxPort.openSerialPort(JRxTxPort.java:50)
at org.openmuc.jrxtx.SerialPortBuilder.build(SerialPortBuilder.java:166)
at de.saltest.home.SomfyCULTest.main(SomfyCULTest.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:282)
at java.lang.Thread.run(Thread.java:748)
java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
From here I'm lost. I have tried many things like copying libraries to different places like suggested in some other posts. I have also changed the classpath and many other things I could think of. However, nothing seems to work. The only thing I find strange is that I try to use java.io. but the code tries to load gnu.io. May be there is some mismatch?
Any help or solution is really appreciated.
Thanks!
What seems to be the solution is to add a plugin to the maven build which produces a JAR with all dependencies included. Like described here: https://www.mkyong.com/maven/create-a-fat-jar-file-maven-assembly-plugin/
However, what's still odd, you have to add the library path like mentioned above:
-Djava.library.path=/usr/lib/jni
For my understanding this should not be necessary anymore. Nevertheless, without the path it is not working.
Did you try to add the native path of the library as start parameter:
-Djava.library.path=/usr/lib/jni
I face the same issue, for resolve the issues, steps that worked for me
Step1. add RXTXcomm.jar and RXTXcomm-2.2pre2.jar in JAVA_HOME/jre/lib/ext
Step2:- create war file using eclipse or anything
Step3: On the client environment these jar should be store in same location
Step4: Add RXTXcomm.jar and RXTXcomm-2.2pre2.jar in JAVA_HOME/jre/lib/ext of client environment.
Note:- If you not geting the data from serial device then check locks on the serial port, It may be other thread or process already occupied or not release the lock.
For checking locks on port,
command is fuser /dev/ttyS0 then
kill -9 PID
I hope this will be work.
Working with centos7

Loading the postgreSQL JDBC driver

I am trying to load a JDBC postgreSQL driver for a Java program. I know this is all over the Internet. I have tried many solutions, but none of them have worked for me.
The problem is that I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError:
classes/com/freire/test/JDBCExample/class
Caused by: java.lang.ClassNotFoundException: classes.com.freire.test.JDBCExample.class
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
And my code looks like this:
package com.freire.test;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class JDBCExample
{
public static void main(String[] argv)
{
System.out.println("JDBC Connection Testing");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("PostgreSQL JDBC Driver not included!");
}
}
}
And the structure of my project looks like this:
myProject
src
com
freire
test
JDBCExample.java
classes
com
freire
test
JDBCExample.class
lib
postgresql-9.2-1003.jdbc3.jar
Compiling works fine:
java -d classes/ src/com/freire/test/JDBCExample.java
But executing produces the error:
java classes/com/freire/test/JDBCExample
Worth to say that I am working on a OS X Mountain Lion.
Any help will be appreciated.
Firstly you need to mention the package names using . instead of / while running the java program:
Go to your classes directory and run JDBCExample as :
java com.freire.test.JDBCExample
But it will now cry for the postgres driver class not found because postgres jar is missing in the classpath.So you need to use the classpath option while running the program and add your postgres jar to the classpath:
for windows:
java -cp .;../lib/postgresql-9.2-1003.jdbc3.jar com.freire.test.JDBCExample
for linux:
java -cp .:../lib/postgresql-9.2-1003.jdbc3.jar com.freire.test.JDBCExample
On Linux execute following:
javac -cp '.:postgresql-9.1-901.jdbc4.jar' postgresjavatest.java
java -cp '.:postgresql-9.1-901.jdbc4.jar' postgresjavatest
It will jdbc drivers for you. make sure jar file is on same location
You need to ensure that the postgresql-9.2-1003.jdbc3.jar is within the class path when you compile and run the program
Try using
javac -cp lib/postgresql-9.2-1003.jdbc3.jar -d classes/ src/com/freire/test/JDBCExample.java
to compile the application and
java -cp lib/postgresql-9.2-1003.jdbc3.jar;./classes com.freire.test.JDBCExample
to run it...
nb As Juned has pointed, technically, you don't need the lib/postgresql-9.2-1003.jdbc3.jar references in the classpath, but consider it an demonstration of how to included compile time dependencies within the complication process ;)

ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I wrote a java servlet program but when i run it, It was showing the Exception java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
My code
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection(url, "username", "pass");
I am using Oracle 10.2.0. I added also ojdbc14.jar and ojdbc14_g.jar.
When I give the below command to command line. I get Error: Main method not found in class oracle.jdbc.driver.OracleDriver
I added also ojdbc14.jar and ojdbc14_g.jar
When adding third party libraries to your application, you must be sure they are in the Build Path of your application. In case of web applications, every third party library must be inside the WEB-INF/lib of the application so when deployed to the server (Tomcat, JBoss, etc.) they can be recognized and loaded when running your application.
Steps to rectify (if running from command prompt)
Step 1- Copy the ojdbc6 jar file from
C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib (Note- this path may differ as per the installation).
Step 2- Paste the ojdbc6 jar file in the Location
C:\Program Files\Java\jre1.8.0_45\lib\ext (Note- this path may differ as per the installation).
Step 3- Now run the programme java -cp . . It should successfully run without any error.

MySQL and JApplet (yes another one)

Before I begin I would like to mention that I have researched this thoroughly and have yet to find a solution which has worked for me (a good 2-3 days of research).
Currently using :
WAMPServer Version 2.1 (Apache service disabled)
Eclipse-jee x64
javac 1.6.0_22
Windows 7 x64
The applet, webpage, and database are all residing on my local computer.
First and foremost my applet works without issues in the Eclipse IDE, however I am constantly recieving the following error when attempting to run it as applet.html with the following script:
<applet code="GUI.class"
name="Some name goes here"
archive="APTracker.jar"
width="1000" height="700">
Your browser is not Java enabled.
</applet>
I have exported my class files using Eclipse IDE which has included the manifest into appletJar.jar.
The Jar exported by Eclipse does NOT contain the mysql-connector library
After assembling my class files I manually extracted the com and org files from the mysql-connector jar and
input them into my appletJar.jar
Following this I signed my applet jar (and confirmed it is signed) with a key which expires in 6 months.
After these steps I still receive the error message shown below.
I have tried replacing localhost with 127.0.0.1 which did not work. I have also tried placing the mysql-connector.jar
in the jre, jdk, and root class files which showed no change.
private final String DRIVER = "com.mysql.jdbc.Driver";
private final String DATABASE_URL = "jdbc:mysql://localhost:3306/javadb";
private final String USERNAME = "xxxxxx";
private final String PASSWORD = "xxxxxx";
private Connection connection = null;
private PreparedStatement selectAllAirports = null;
private ResultSet resultSet;
private ResultSetMetaData metaData;
/* Establish PreparedStatements */
public ResultSetTableModel()
{
try
{
//establish connection to database
connection = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
//load driver class
Class.forName( DRIVER );
//create prepared statements
selectAllAirports = connection.prepareStatement( "SELECT asciiname, latitude, longitude, elevation, timezone, country_code FROM geoname;" );
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
//System.exit(1);
}
catch ( ClassNotFoundException classNotFound )
{
System.out.println("ClassNotFoundException triggered.");
classNotFound.printStackTrace();
}
}
This is the error message which I receive:
C:\Users\Mr.\Desktop\Applet>appletviewer applet.html
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/javadb
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at ResultSetTableModel.(ResultSetTableModel.java:38)
at GUI.(GUI.java:20)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:785)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:714)
at sun.applet.AppletPanel.run(AppletPanel.java:368)
at java.lang.Thread.run(Thread.java:662)
java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Vector.java:427)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
at GUI.init(GUI.java:60)
at sun.applet.AppletPanel.run(AppletPanel.java:424)
at java.lang.Thread.run(Thread.java:662)
Note that recent JDBC drivers don't need the Class.forName() call if the service loader method is supported.
The current Connector/J version does support that, but by including only the org and com directories of the JDBC driver you "broke" it: The service loader mechanism depends on files under the META-INF directory.
So with your setup you would indeed need the Class.forName() call. But in your code that code is after the attempt to get the connection, which won't do any good.
So do one of those:
Add the relevant service files from the JDBC driver (under META-INF/services) to your jar file (and get rid of the unnecessary Class.forName() call) or
Put the Class.forName() call before the DriverManager.getConnection() call.
Rather than trying to manually put the MySQL class files into your APTracker.jar, why not just include the MySQL jar on the applet's classpath?
I suspect there is something in the MySQL jar file's META-INF directory that you need - a ServiceLoader configuration file or some such.
Things to consider are:
Do you have mysql-connector-java-5.1.10.jar or any related connector in your machine? If none, ask it in google?
If you have, paste the connector at C:\Program Files\Java\jdk...\jre\lib\ext directory.
Edit the applet tag on archive as archive = APTracker.jar, mysql-connector-java-5.1.10.jar
Paste again the mysql-connector-java-5.1.10.jar to where the files like .html, .class and the like are located.
I guess the MySQL JDBC jar is missing.
you can download that jar from: http://www.mysql.com/downloads/connector/j/

Categories