runtime error: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver - java

I am new to mysql and jdbc and I am getting the error in this title. I have been searching all day and cannot find a solution that works for me.
What I have tried:
uninstall/reinstall mysql, copy paste mysql-connector-java-5.1.25-bin.jar and ojdbc7.jar to same location as the .class file I am trying to run, rebuilt the program in a different directory, and probably a couple other things.
I am using notepad++ for coding and the windows command prompt to compile and run. it compiles fine but I try to run with
C:\Projects\bin>java -cp . ClientBase
The output is:
java.lang.ClassnNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassloader$1.run(URLClassLoader.java:336)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:432)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:188)
at ClientBase.main(ClientBase.java:21)
Goodbye.
// import packages
import java.sql.*;
// create class ClientBase
public class ClientBase{
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/CLIENTBASE";
// Database credentials
static final String USER = "root";
static final String PASS = "";
// Begin method main
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, address, address 2, city, phone, state, zip, fax FROM CLIENTBASE";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next()){
// Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
String address = rs.getString("address");
String address2 = rs.getString("address2");
String city = rs.getString("city");
String phone = rs.getString("phone");
String state = rs.getString("state");
String zip = rs.getString("zip");
String fax = rs.getString("fax");
// Display values
System.out.print("ID: " + id);
System.out.print(" Name: " + name);
System.out.println("Address:" + address);
System.out.println(address2);
System.out.print("City:" + city);
System.out.print(" State: " + state);
System.out.println(" Zip: " + zip);
System.out.print("Phone: " + phone);
System.out.println(" Fax: " + fax);
} // end while
// clean up
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
// Handle errors for Class.forName
e.printStackTrace();
}finally{
// finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se){
se.printStackTrace();
} // end finally
} // end try
System.out.println("Goodbye.");
} // End method main
} // end class ClientBase
I should also say that I am going off an online tutorial for this code. It is not exactly how they have it as I decided to make something a little different than theirs, but it is generally the same. I don't think it is a code problem though from what the error is.
Any help would be appreciated! I'm going crazy!

You need to add a connector library to the Runtime classpath:
java -cp .;mysql-connector-java-5.1.25-bin.jar ClientBase
My example uses Windows classpath separator ";", on other systems it may be different (":" on Linux/Mac). It also assumes, that mysql-connector-java-5.1.25-bin.jar is located on the same folder. If it's not the case, then put a path to the library instead of the plain name.
ClientBase stands for Java class file name here
c:\>javac Test.java
c:\>java -cp .;F:\CK\JavaTest\JDBCTutorial\mysql-connector-java-5.1.18-bin Test

I was also get same problem :-
How I solved for Linux system.
1.) Download file mysql-connector-java-5.1.18-bin.jar from given link or other.
2.) Then paste it to same folder or directory of your class or file (on where you want connection to present)
3.) Now use the following command by your linux command prompt.
java -cp .:mysql-connector-java-5.1.18-bin.jar YourFileName ..
Thats all you need to do... :)

if u use netbeans,do following
1.Open Netbeans IDE
2.Right-click your Project.
3.Select Properties.
4.On the left-hand side click Libraries.
5.Under "Compile" tab - click Add Jar/Folder button.
6.Select Downloaded "mysql-connector-java-5.1.25-bin.jar" file (Download Connector/J from dev.mysql.com)
7.Click OK
Run Again... Its work.

What did you import ?
From the documentation: http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-connect-drivermanager.html
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.jdbc.*
// or you will have problems!
Comment:
Why are you using notepad++ ? install an IDE (Eclipse/Netbeans/IntelliJ) - it'll be much easier to locate such problems (un-included jars for example)

Add mysql.connector-java-x.x.x-bin.jar to your libraries folder. No need to import anything. Have a good one.

If You Are Using Swing you have to add External Jar of my-sql-connect
else if You are Using jsp servlet You have to add External jar and Copy that Jar into WEB_INF/lib project folder

Related

how to load the resources from the nested jar files resources

i have one jar file inside it there is lib folder which contain all the jar files which we mentaion in the pom file.
here the question is : how is read the all the external jar (pom file jars) files resources.
example : example.jar has dependies in lib folder file1.jar & file2.jar i want to read the resource of both file1.jar and file2.jar
how JVM loads the all the resources?
This is a very unusual situation, maybe much better approach which is usually used is "flatterning" the jars, so you won't have dependent jars in some folder inside an "outer" jar, but instead all packages from dependent jars will become packages of the outer jar residing next to your own code that probably is in the outer jar anyway.
Maven has shade plugin for this, and this is usually the way to go.
One noticeable exception is a spring boot applications packaged as JARs that work just like you've said (they put dependent jars into BOOT-INF/lib library, so technically its jars inside jar).
They have their own reasons to work like this which are way beyond the scope of this question, but the relevant point is that they had to create a special class loader that would handle this situation. Java out of the box can read classes from filesystem or from regular jar, but in theory java application can read the binary code from any place (Remote Filesystem, Database, Jar inside Jar whatever) as long as you implement the class loader that can find and load the resources from there.
In general I would recommend not to mess with Class Loaders which are pretty advanced concepts unless you really know what you're doing. Most of java programmers do not really create their own class loaders.
venkateswararao yeluru please follow below code to read data from jar file:
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";***`
strong text`***
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Underclassmen("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
System.out.println("Goodbye!");
}// end main
}// end FirstExample

"given file does not exist" issue with UCanAccess connection

I'm trying to connect to a Microsoft Access database in Eclipse (Mars 4.5.0; Java 1.8) on a Mac (el capitaine). I keep getting the error:
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.4 given file does not exist: Users/sebastianzeki/Documents/BEST2RFA_DBv1.accdb
This is my code:
import java.sql.*;
public class DbAccess
{
public static void main(String[] args)
{
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://Users/sebastianzeki/Documents/BEST2RFA_DBv1.accdb;");
Statement stment = conn.createStatement();
String qry = "SELECT * FROM Table1";
ResultSet rs = stment.executeQuery(qry);
while(rs.next())
{
String id = rs.getString("ID") ;
String fname = rs.getString("Nama");
System.out.println(id + fname);
}
}
catch(Exception err)
{
System.out.println(err);
}
}
}
I'm sure its something to do with the pathname slashes but I've tried every permutation and still get the same error.
I'm not familiar with Mac file systems but have you tried "jdbc:ucanaccess:///..." (including an extra slash)?
Explanation:
The path to the database file immediately follows the jdbc:ucanaccess:// prefix of the connection URL, so for
jdbc:ucanaccess://Users/sebastianzeki/Documents/BEST2RFA_DBv1.accdb;
the path to the database file is
Users/sebastianzeki/Documents/BEST2RFA_DBv1.accdb
which is interpreted as a relative path, relative to the OS-level current directory in effect when the Java application was launched.
In order for the path to be interpreted as an absolute path it must start with a forward slash, i.e.,
/Users/sebastianzeki/Documents/BEST2RFA_DBv1.accdb
therefore the connection URL needs to be
jdbc:ucanaccess:///Users/sebastianzeki/Documents/BEST2RFA_DBv1.accdb
Open your MS Access Database
Go on FILE
Select OPEN Database
Right click your database and select COPY LINK
Paste the link after jdbc:ucanaccess://

Java database query not printing out in console

I'm creating my first Java program that pulls data from a MySql database. I'm having trouble getting the result from a query to print in console. My program compiles without error but out.print command not displaying content in console. I'm using Intellij IDEA 15.0.2.
import java.sql.*;
import static java.lang.System.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/animal";
String user = "username";
String pwd = "password";
try {
Connection connection =
DriverManager.getConnection(url, user, pwd); // Get Connection
Statement statement = connection.createStatement(); // Create Statement
String query = "SELECT * FROM animal";
ResultSet resultSet = statement.executeQuery(query); // Execute Query
while (resultSet.next()) { // Process Results
out.print(resultSet.getInt("animal_id"));
}
} catch (SQLException se) { }
}
}
To print out to console the correct command is
System.out.print("Whatever you want to print");
not
out.print("Whatever you want to print");
Yeah.. as BradStell said you have to use
System.out.print(resultSet.getInt("animal_id"));
instead of
out.print(resultSet.getInt("animal_id"));
Another suggestion that I would like to make is Always do something on catching an exception. You have no code in the catch block. Atleast try to print the exception there. That would help you very much in finding errors in your code .
The problem was with the database driver. I needed to use the forName method(), and add the driver url for MySql. After I successfully implemented this class I was able to create sql queries without issue. Thanks for the tip with the exception handling #Senthil Vidhiyakar
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.print("Working");
}
catch (Exception e){ System.out.println("Not working");}
I also had to connect the mysql connector jar. The process for doing this in Intellij IDEA is as follows.
File >> Project Structure "The project structure window will appear then on the left side menu click Modules in the main content area click on the Dependencies tab. Next click the green +. Choose option 1 JARs or directories. Finally, navigate to the mysql connector jar. Then click apply, and ok."

Compiling a Java project on Unix using external library mysql-connector-java-5.1.24-bin.jar

I have a java project that read a database in my local drive and is compiling using Eclipse.
Below is the code that works fine for me.
package SQLtest;
import java.sql.*;
public class SQLtest {
public static void main(String[] args) throws Exception {
Connection connect = null;
Statement statement = null;
ResultSet resultSet = null;
String query = "SELECT * FROM abc.publicationlist LIMIT 10";
// This will load the MySQL driver, each DB has its own driver
// Setup the connection with the DB
// host = localhost, user = root , password = None, database = abc
try{
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/abc?"+ "user=root&password=");
statement = connect.createStatement();
resultSet = statement.executeQuery(query);
while(resultSet.next()){
String id = resultSet.getString("id");
String pubyear = resultSet.getString("pubyear");
String title = resultSet.getString("title");
String jconfname = resultSet.getString("jconfname");
String authors = resultSet.getString("authors");
String authorids = resultSet.getString("authorids");
System.out.println(id + ":" + pubyear + ":" + title + ":" + jconfname + ":" + authors + ":" + authorids);
}
}
catch ( SQLException err ) {
System.out.println( err.getMessage( ) );
}
System.out.print("End of program!!!");
}
}
Now I want to move everything to a server using SSH (secure shell). I already move all the database into mysql database server on SSH.
The server name is no longer localhost but change to xxxxxxxx
The username : myname
the password : zzzzzz
I know that I need to change these in the code itself. What I am not familiar with is using a Unix environment to compile a java project that include some external libraries such as mysql-connector-java-5.1.24-bin.jar
Here is the 2 command that I used
[...... src]$ javac -classpath ".:/home/myname/SQLtest/lib" SQLtest/SQLtest.java
[...... src]$ java -cp ".:/home/myname/SQLtest/lib" SQLtest.SQLtest
and I get these log error which I don't understand:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at SQLtest.SQLtest.main(SQLtest.java:16)
How can I solve this problem ? I am really new to Unix system.
try putting individual jars like -classpath ".:/home/myname/SQLtest/lib/mysql-connector-java-5.1.24-bin.jar" and moreover it is a good idea to add the jars into permanent classpath environment vairable and export that.

Connecting a Microsoft Access Database to Java using JDBC and compiling

for a school database project we are making a database program (user GUI and the database). Using Microsoft Access 2010 I created the database and populated it with some sample data, and saved it in .mdb format and placed it in my project folder.
When running it in eclipse the following code works fine, connects and even retrieves the query. However I find that I am unable to export the code to a jar and run it (which is required for the project, give them a working copy of your program on a CD or flash drive), and I'm also unable to port the code over to Netbeans to have it work, as well as trying to compile on a Linux machine.
I assume this is a problem with including drivers or trying to use Microsoft access. The error I get when running the jar or running on Netbeans is given below the code. So I ask either how do I include drivers to make the program portable, or how else can I approach this problem?
Thanks in advance
import java.sql.*;
public class JDBCTest {
static Connection connection;
static Statement statement;
public static void main(String args[]){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=TLDATABASEDBM.mdb";
connection = DriverManager.getConnection( database ,"","");
buildStatement();
executeQuery();
}catch(Exception e){
e.printStackTrace();
System.out.println("Error!");
}
}
public static void buildStatement() throws SQLException {
statement = connection.createStatement();
}
public static void executeQuery() throws SQLException {
boolean foundResults = statement.execute("SELECT * FROM tblStaff AS x WHERE City='Calgary'");
if(foundResults){
ResultSet set = statement.getResultSet();
if(set!=null) displayResults(set);
}else {
connection.close();
}
}
public static void displayResults(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columns=metaData.getColumnCount();
String text="";
while(rs.next()){
for(int i=1;i<=columns;++i) {
text+=""+metaData.getColumnName(i)+":\t";
text+=rs.getString(i);
//text+="</"+metaData.getColumnName(i)+">";
text+="\n";
}
text+="\n";
}
System.out.println(text);
}
}
The error mentioned above:
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(JdbcOdbc.java:3073)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(JdbcOdbcConnection.java:323)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:174)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at tldatabase.DataConnect.makeConnection(DataConnect.java:35)
at tldatabase.Main.main(Main.java:24)
I know the post was years ago but I felt like answering the question for those who are just experiencing this right now. It took me a while to know the answer to the question so here's the solution:
http://wiki.netbeans.org/FaqSettingHeapSize
Follow the "Running the 32-bit JVM".
All you have to do is find the netbeans.conf in the installation folder of your netbeans and change the directory from something like this:
netbeans_jdkhome="C:\Program Files\Java\jdk1.6.0_24"
to this:
netbeans_jdkhome="C:\Program Files (x86)\Java\jdk1.6.0_21"
The problem is netbeans might be running in 64 bit but MS Access only support 32-bit. So doing this would hopefully solve the problem. Also make sure to install this:
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=23734
The main problem lies in the line:
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=TLDATABASEDBM.mdb";
Make sure that the .mdb file is in the correct directory.
Check the file extension as .mdb or .mdbacc.
Also, if you want to use the same DSN every time, it is better to add the DSN(Data Source Name) into the respective system on which the mdb is stored.
I think that your app do not see TLDATABASEDBM.mdb in current directory. You can give full path to this file in connection string or add system DSN in ODBC Manager and then connect to it with connection string like: jdbc:odbc:TLDATABASEDBM
Honestly, I dont like what I am going to say... but, it solved the same issue for me... mysteriously... :(((
on the line where you are defining the database variable, I changed ...(.mdb)... into ...(.mdb, *.accdb)...
All the best for figuring out what difference that made!
package javaapplication1;
import java.sql.*;
public class MSaccess_archive {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// set this to a MS Access DB you have on your machine
String filename = "mdbTEST.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;}"; // add on to the end
// now we can get the connection from the DriverManager
Connection con = DriverManager.getConnection( database ,"","");
Statement stmt = con.createStatement();
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Result that came from our query
if (rs != null)
while ( rs.next() ){
System.out.println("Name: " + rs.getInt("Age") + " ID: "+rs.getString("Course"));
}
stmt.close();
con.close();
}
catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}

Categories