"java.lang.ClassNotFoundException" when executing Java code - java

I get a java.lang.ClassNotFoundException, when I execute the below code.
Could someone explain me why I am facing this? All I need to do is to connect to the db and fetch some values from it. Is it a problem with the eclipse that I use?
import java.sql.*;
public class test_sample {
public static void main(String[] args) {
try {
System.out.println("Test1");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("Test2");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:#ussbazudb126.ussb.winson.net:1521/epdev", "manager", "<<PASSWORD>>");
System.out.println("Test3");
// Statement st = con.createStatement();
PreparedStatement meta = con.prepareStatement("select project from isac_extract");
System.out.println("Test4");
ResultSet rset = meta.executeQuery();
while (rset.next()) {
String project = rset.getString(1);
System.out.println(project);}
}
catch (Exception e){
e.printStackTrace();
}
finally {System.out.println("Final Block");}
}
}

Go to Project properties (Project -> Properties) -> Java Build Path -> Libraries -> Add external JARs -> select jar with Oracle Driver from your filesystem (you can download it from here if you haven't already). That should help.

Download appropriate Oracle JDBC driver from here. If you are using Eclipse you need to add ojdbc14.jar which contains the OracleDriver class to your build path. It is usually located in:
{ORACLE DRIVER INSTALL PATH}\jdbc\lib\ojdbc14.jar
If you are not using an IDE you need to add the path to that JAR to your -classpath option.

Most likely : oracle.jdbc.OracleDriver is missing from your classpath, check it.

Include Oracle JDBC driver in your classpath.

For Oracle 11g, you need to place
ojdbc6.jar
in Java Classpath. The ojdbc.jar can be found on Oracle home directory E:\app\shyam\product\11.2.0\dbhome_1\jdbc\lib.
We can simply put ojdbc6.jar in C:\Program Files\Java\jre7\lib\ext directory instead of defining Java Classpath also.

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.)

running Postgresql in Java [duplicate]

I am having some difficulty in making connectivity with Java and PostgreSQL Database.I have download the JDBC4 Postgresql Driver, Version 9.2-1002 driver and properly set the application ClassPath. My code is as under
import java.sql.*;
public class JavaPostGreSQLConnectivity
{
public static void main(String[] args)
{
DB db = new DB();
db.dbConnect("jdbc:postgresql://127.0.0.1:5432/TestDB", "postgres","pwd");
}
}
class DB
{
public DB() {}
public void dbConnect(String db_connect_string, String db_userid, String db_password)
{
try
{
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
System.out.println("connected");
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
Upon running I am getting the below error
Is it complaining about
Class.forName("org.postgresql.Driver");
If so then what will be the driver name? However, I followed this for my learning purpose.
However, If I do
C:\Program Files (x86)\Java\jdk1.7.0\bin>java -cp C:\Users\pos
tgresql-9.2-1002.jdbc4.jar; JavaPostGreSQLConnectivity
connected
It works.Why I need to explicitly mention the driver again when I have already placed it in the classpath properly? Is there any alternative way (I just want to put the JAR file in Classpath and the program should read from there)?
Thanks in advance
The driver name is OK. It is the same as mentioned in the official docs of the driver. Therefore the driver is just not in the classpath.
You say:
I [...] properly set the application ClassPath
On the other hand you start the program by just calling:
java JavaPostGreSQLConnectivity
In that case no PG driver is on the classpath. You have to add it by hand using someting like
java -cp postgresql-jdbc4.jar JavaPostGreSQLConnectivity
EDIT The question has been changed while typing, hence the duplication.
You added the jar only in you IDE. This helps the IDE to compile your code. If you start the program using you IDE then the IDE will also set the classpath for you. But if you don't start via the IDE then nobody knows the correct classpath and it has to be set by hand.
Your options are:
start always via IDE
make some batch script which hides the setting of the classpath (common solution)
set the CLASSPATH environment variable (does not scale with other Java applications)
make an "Executable Jar" and set the classpath there. (Search this site using that term).
put the jar into a place where the JVM picks it up automatically (e.g. in the lib/ext directory of the JRE). But polluting the JRE/JDK libs is the worst option.
Note: This is all basic Java knowledge and has nothing to do with PostgreSQL.

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

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.

Error while making connection to Oracle database in JDBC

I have written a code to check whether connection is successful or not.
But its giving error.
I have a oracle 10g express edition instsalled on my computer.
try{
String url="jdbc:oracle:thin:#//localhost:1521:XE";
String driver= "oracle.jdbc.driver.OracleDriver";
Class.forName(driver);
System.out.println(" Driver loaded ");
Connection con = DriverManager.getConnection(url,"system:,"manager");
System.out.println("Connection Successful");
} //catch block
The error given is:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
Thanks for help.
you need to add oracle jdbc driver (jar) to your class path.
Looks like the JAR file containing the oracle.jdbc.driver.OracleDriver class is simply not on your classpath. Find it and fix that problem by adding the location (e.g., via the -cp option to java; the details of how to fix it will vary by the kind of application you're building).
Add ojdbc.jar in classpath.
Check this for How to Add JARs to Project Build Paths in Eclipse
You have to put the oracle_jdbc.jar file in the same folder of your code, or anywhere else and add that folder to your classpath.

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