Jar File Error (java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver) - java

Sir in Netbeans when I run program it runs successfully but when I make jar file and run it then there is this error :
java.lana.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
Please answer me that how to solve that exception.
Here is my code:
public class DatabaseManager {
static Connection con;
static{
System.out.println("Connecting To Database ... ... ...");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Pepsi");
} catch (ClassNotFoundException | SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
System.exit(0);
Logger.getLogger(DatabaseManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have also used ucanaccess me libariers for direct access to database.
con = DriverManager.getConnection("jdbc:ucanaccess:C:\\Users\\Administrator\\Documents\\NetBeansProjects\\Pepsi\\Pepsi.accdb");
When I ran java while the exception comes but in Netbeans it works properly.

It is running in netbeans IDE because you have all java reference libraries added in your project. Please verify your classpath when running jar directly. I guess your are not having rt.jar in your classpath.
Check this if your are using Java 8 java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

I guess the some classes are not properly added to your jar file as external dependencies. Please verify that all the external jar files that you are using in your project are successfully added to your jar file.

Related

ClassNotFound & No Suitable Driver, where did I go wrong?

I have created a program that works perfectly in the IDE on NetBeans, but anytime I build the .jar file, the database connection stops working. I've already added the CLASSPATH to the MySQL Connector, as well as defined Class.forName("com.mysql.jdbc.Driver"); Still nothing..
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/gearheads";
Connection conn = DriverManager.getConnection(url,"root","HellOnEarth202021");
Statement stmt = conn.createStatement();
ResultSet rs;
String pid = txt_staffID.getText();
rs = stmt.executeQuery("SELECT name,timeraccess FROM staff WHERE staffid = '"+pid+"'");
while ( rs.next() ) {
String timeraccess = rs.getString("timeraccess");
String staffName = rs.getString("name");
getLogin = staffName;
System.out.println(staffName);
System.out.println("Users Admin Level: " + timeraccess);
if ( timeraccess.equals("1")) {
this.dispose();
new menu().setVisible(true);
System.out.println("Access Granted");
}else
System.out.println("Access Restricted.");
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
txt_staffID.setText(e.toString());
System.err.println(e.getMessage());
}
This, as it stands, outputs:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Where taking out the Class.forName outputs:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/gearheads
Please help me. This link is a screenshot of my libraries.
My Libraries:
If its runnning correctly inside Netbeans, then the MySQL driver is correct.
You have to search for Manifest file (MANIFEST.MF) and probably will have to unjar the contents of the driver inside your own JAR file.
I'll leave this answer by now, but will try to gather the details to bring it back here.
I also use NetBeans and when I generate the JAR file, its already copying the dependant libraries and generating the correct MANIFEST.MF.
I ended up with the following structure
MyProject\dist\lib\JdbcDriver.jar
and
MyProject\dist\MyProject.jar
Inside MyProject.jar, I have the following MANIFEST.MF:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.9.7
Created-By: 1.8.0_201-b09 (Oracle Corporation)
Class-Path: lib/JdbcDriver.jar
X-COMMENT: Main-Class will be added automatically by build
Main-Class: myproject.MyMainClass
Please, verify with you are copying the lib folder altogether with your JAR file.
Just to leave here the final solution (#Nick Media final comment): you have to check "Copy Dependent Libraries" in Build>Packaging Project Properties.
It is not clear exactly what you are doing wrong, but you are clearly doing something incorrectly:
It is often better to use DriverManager.getConnection rather than Class.forName and a specific driver class name. This is the approach recommended by the Oracle Java Tutorial; see https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html
If you are loading the driver via its classname, use com.mysql.jdbc.Driver with MySQL Connector/J 5.x and com.mysql.cj.jdbc.Driver with MySQL Connector/J 8.x.
If this is a webapp, make sure that the relevant driver JAR file is actually in your WAR file, and/or that it is being deployed correctly.
If this is a command line app, make sure that you include the driver JAR on the runtime classpath. (Especially if you are trying to run it outside of your IDE.) Alternatively, consider creating a shaded JAR that included all of the apps dependencies. (It is a bit hard to advise since you haven't told us if you are using a build tool like Ant, Maven, Gradle, etc.)
The driver doesn't actually need to be a compile time dependency, though there is little harm in doing that. (The harm is that you might accidentally add imports to the MySQL implementation classes to your app ... and run into problems.)

JAVA Runnable .JAR File incomplete execution. Eclipse IDE Runs to completion

Running into an issue with a JAVA application that I'm hoping someone can provide some clarity to. I have a simple Java Application which is being built in the Eclipse IDE. I have JRE 1.8.0_251 installed on PATH.
My application at a basic level performs the following:
Load a properties file
Connect to a MSSQL Database based on that SQL File (using java.sql.Connection)
Queries some data.
Updates some data.
This all works without issue in Eclipse. However, when I export my file to a runnable .JAR file, it appears to stop after attempting to initialize the database connection. However, it does not throw a SQLException and never returns from the method. I checked my .jar file in 7ZIP to make sure that the SQLJDBC42.jar was packaged in the folder and it was.
The last log line I see when my runnable JAR executes is: Log.info("Connecting to Database...") however, all items run / and are logged in Eclipse execution.
Any ideas? Code below:
public void ConnectDatabase() {
Log.info("Connecting to Database...");
try {
//Connect to Database and Log success.
ConnectionInstance = DriverManager.getConnection(connectionURL);
Log.info("Database Connection Successful.");
} catch (Exception e) {
Log.info(String.format("ERROR | DATABASE: %s", e));
//System.exit(0);
}
Log.info("Leaving Database Method.");
}

JavaFX8, SQLite(Embedded) exe, exec jar can't read/update the runtime database

I am creating a simple desktop application using JavaFx8 and SQLite and Eclipse Neon IDE. The Application works fine when launched to test from Eclipse. But If I create an executable jar or a Windows Exe file, it doesn't read/update the database.
Here's the code snippet used for creating and reading database.
private Connection loadPropertiesFileSQLite() throws SQLException, ClassNotFoundException {
try {
inputStream = new FileInputStream("databasesqlite.properties");
properties.load(inputStream);
Class.forName("org.sqlite.JDBC");
// database path, if it's new database, it will be created in the project folder
conSQLite = DriverManager.getConnection("jdbc:sqlite:Application.db");
System.out.println("Database Opened Successfully.");
} catch (Exception e) {
System.out.println("DDDD");
e.printStackTrace();
}
return conSQLite;
}
The connectors and jars I'm using are these:
The database is created in embedded mode when the user runs the application for the first time.
I have searched and tried scores of combinations from changing the location of database in DriverManager.getConnection("jdbc:sqlite:Application.db");
to many other things. Is there anything big that I'm missing here?
Are you using the properties file for nothing?
there is my config: sqlite-jdbc-3.7.15.jar
//auto commit on the connection.
conSQLite.setAutoCommit(true);
and check if do you have a permission at the file "Application.db".
The key is to use conSQLite = DriverManager.getConnection("jdbc:sqlite::resource:File:\\{some_path}\\Application.db");
instead of
conSQLite = DriverManager.getConnection("jdbc:sqlite:Application.db");
Now it works all fine.

Executable Jar with Dependency on dll

I am attempting to deploy a swing application that uses a dll to facilitate a database connection (using sqljdbc4 jar that depends on sqljdbc_auth.dll). My deployment strategy is creating an executable jar file. The problem is that I cannot get the functions that rely on the sqljdbc_auth.dll to work in the executable jar I create.
I can get the project working fine in eclipse by using any of the following methods:
Reference the folder containing the dll in the build path configuration by specifying a Native library location on the Source folder
Put the dll in C:\Windows\System32 directory
Add the following VM argument referencing the relative path of the dll folder in my project "-Djava.library.path=path/to/dllfolder"
The 4th method I have tried is to load the dll directly in code via the following line. System.load("C:/Users/Me/Desktop/sqljdbc_auth.dll");
I have been unsuccessful with this approach and get the following error.
Mar 20, 2015 4:18:44 PM com.microsoft.sqlserver.jdbc.AuthenticationJNI <clinit>
WARNING: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path
However, that error doesn't come directly from the line of code that loads the library, it seems to come afterwards when the sqljdbc library is trying to load the dll for use in making the connection.
Either way, I cannot get anything of the above methods working when I deploy the app as an executable jar file via the export functionality of eclipse. The only thing I can get is the previously mentioned error message.
The following sample application produces the same result.
public class TestApp {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame mainFrame = new JFrame();
mainFrame.setSize(300,300);
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
try{
//System.load("C:/Users/Me/Desktop/sqljdbc_auth.dll");
String serverName = "local";
String databaseName = "test_database";
String connString = "jdbc:sqlserver://" + serverName + "; databaseName=" + databaseName + ";integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(connString);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select distinct name from test_table");
rs.next();
JOptionPane.showMessageDialog(null, "From db: " + rs.getString(1), "Test", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e.getMessage(), "Test", JOptionPane.INFORMATION_MESSAGE);
} catch (ClassNotFoundException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e.getMessage(), "Test", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, e.getMessage(), "Test", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
}
I've read tons of posts on using dlls with executable jars and they all seem to reference using this System.load method. Ironically, that is the one thing I can't get working. I know I have the right dll; however, because I can get other methods to work in the IDE environment. I don't care if the dll is packaged with the executable jar or not, I just want it to work!
I would presume this has something to do with putting the dll's in your library
(In Eclipse, Properties->Java Build Path->Libraries).
When you export the jar, you also will have the option of exporting the library files into a folder.
If you decompile the Jar after that, you'll notice that there's a manifest file, and in it, paths to where your library files are (based on the export, which created a library folder for you, generally jarname_lib).
When you export, you have the option to save as ANT file, which you can then edit to change the export location of the library files to a folder name of your choice. You can then add this edited ANT file to your build so that it happens whenever you build the project:
(In Eclipse, Properties->Builders->New)

problem using JDBC to connect to mysql

I'm trying to set up a connection between my applet and my mysql server using jdbc
I added the jar mysql-connector-java-5.1.14-bin.jar to the project
then I used this code
public void databaseTesting(){
Connection con;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root","");
System.err.println("connected !");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM `test`.`test`;");
while (rs.next()) {
int A = rs.getInt("columnA");
int B = rs.getInt("columnB");
System.err.println("A "+A+" B "+B);
}
} catch (SQLException e) {
System.err.println("failed to connect");
} catch (InstantiationException e) {
System.err.println("InstantiationException");
} catch (IllegalAccessException e) {
System.err.println("IllegalAccessException");
} catch (ClassNotFoundException e) {
System.err.println("ClassNotFoundException");
}
}
and for some reason I keep getting ClassNotFoundException.
edit
the jar is added to the build path and appears in the Referenced Libraries.
the exception is thrown by
Class.forName("com.mysql.jdbc.Driver").newInstance();
Anybody got an idea why ?
Thanks in advance jason
Do you run this application through eclipse? Is it a Dynamic web project, if so then try adding the jar file to the WEB-INF\lib folder
Then the JAR is not in the runtime classpath.
Since you explicitly mentioned "project", I'll assume that you're using an IDE. You have to add the JAR file to the so-called Build Path (which represents both the compiletime and runtime classpath). In Eclipse for example, rightclick the JAR file you dropped in the project folder, choose Build Path > Add to Build Path and that should be it.
See also:
Mini tutorial with JDBC and MySQL
Update: If it keeps complaining, then it is still not in the runtime classpath. Either you did it wrong or the runtime environment didn't use this JAR. Did you run it as a Java Application or as a Java Applet? (even though it's a bad practice to do JDBC inside an applet). If you're actually running this as an applet, it has got to be in the runtime classpath of the applet as well. You can specify it in the archive attribute/parameter of the applet.
Your code is OK! It will work when:
Your mysql-connector-java-5*-bin.jar is in place.
The login & password are correct.
Your database exists
Your table exists
Your ColumnA and ColumnB are integers
If you are using an IDE just add the jar to the Libraries.

Categories

Resources