I'm trying to compile and run the sample code shown below, but it gives me a ClassNotFoundException. I was wondering what the best way to resolve this issue in eclipse would be, as I'm new to the software. I've read many answers on the site about this exception and what may cause it, but I cannot understand alot of the solutions, so I would greatly appreciate if someone could give me a simple explanation for what's causing the problem. Thank you.
public class Model{
public static void main(String[] args) throws Exception
{
Model myDbTest = new Model();
myDbTest.displayDbProperties();
}
private java.sql.Connection con = null;
private final String url = "jdbc:microsoft:sqlserver://";
private final String serverName= "localhost";
private final String portNumber = "1433";
private final String databaseName= "pubs";
private final String userName = "user";
private final String password = "password";
// Informs the driver to use server a side-cursor,
// which permits more than one active statement
// on a connection.
private final String selectMethod = "cursor";
// Constructor
public Model(){}
private String getConnectionUrl(){
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
private java.sql.Connection getConnection(){
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) System.out.println("Connection Successful!");
}catch(Exception e){
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
/*
Display the driver properties, database details
*/
public void displayDbProperties(){
java.sql.DatabaseMetaData dm = null;
java.sql.ResultSet rs = null;
try{
con= this.getConnection();
if(con!=null){
dm = con.getMetaData();
System.out.println("Driver Information");
System.out.println("\tDriver Name: "+ dm.getDriverName());
System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
System.out.println("\nDatabase Information ");
System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
System.out.println("Avalilable Catalogs ");
rs = dm.getCatalogs();
while(rs.next()){
System.out.println("\tcatalog: "+ rs.getString(1));
}
rs.close();
rs = null;
closeConnection();
}else System.out.println("Error: No active Connection");
}catch(Exception e){
e.printStackTrace();
}
dm=null;
}
private void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
}
The error is printed as:
java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriverError Trace in getConnection() : com.microsoft.jdbc.sqlserver.SQLServerDriver
Error: No active Connection
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Model.getConnection(Model.java:30)
at Model.displayDbProperties(Model.java:48)
at Model.main(Model.java:6)
It looks like the JAR of your JDBC driver is not included in the classpath when running your source code. But as others mentioned, stacktrace is probably needed to further help you.
It looks like you haven't MsSQLServer jdbc driver in your .classpath
Look here
Related
What I am trying to do:
I want to connect my MS Access Database with Java 8. So I am using "UcanAccess" driver to connect to my Database.
What I am using:
Eclipse, Java 8, and MS Access database
My MS Access database path:
C:/Users/dave/My_WorkSpace/Eclipse_Workspaces/workspace-jsp/Database11.accdb"
I have the following Jar files in my project:
mysql-connector-java-5.1.35-bin.jar
ucanaccess-2.095.jar
jackcess-2.1.2.jar
hsqldb.jar
commons-lang3-3.4.jar
commons-logging-1.2.jar
Error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/builder/CompareToBuilder
at com.healthmarketscience.jackcess.impl.RowIdImpl.compareTo(RowIdImpl.java:106)
at com.healthmarketscience.jackcess.impl.IndexData$Entry.compareTo(IndexData.java:2039)
at com.healthmarketscience.jackcess.impl.IndexData$Entry.compareTo(IndexData.java:1847)
at java.util.Collections.indexedBinarySearch(Unknown Source)
at java.util.Collections.binarySearch(Unknown Source)
at com.healthmarketscience.jackcess.impl.IndexData$DataPage.findEntry(IndexData.java:2570)
at com.healthmarketscience.jackcess.impl.IndexData.findEntryPosition(IndexData.java:844)
at com.healthmarketscience.jackcess.impl.IndexData.access$3700(IndexData.java:47)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.updatePosition(IndexData.java:2335)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.restorePosition(IndexData.java:2273)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.restorePosition(IndexData.java:2256)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.beforeEntry(IndexData.java:2218)
at com.healthmarketscience.jackcess.impl.IndexCursorImpl.findPotentialRow(IndexCursorImpl.java:376)
at com.healthmarketscience.jackcess.impl.IndexCursorImpl.findFirstRowByEntryImpl(IndexCursorImpl.java:282)
at com.healthmarketscience.jackcess.impl.IndexCursorImpl.findFirstRowByEntry(IndexCursorImpl.java:153)
at com.healthmarketscience.jackcess.impl.DatabaseImpl$DefaultTableFinder.findRow(DatabaseImpl.java:2074)
at com.healthmarketscience.jackcess.impl.DatabaseImpl$TableFinder.findObjectId(DatabaseImpl.java:1953)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.readSystemCatalog(DatabaseImpl.java:858)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.<init>(DatabaseImpl.java:518)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.open(DatabaseImpl.java:389)
at com.healthmarketscience.jackcess.DatabaseBuilder.open(DatabaseBuilder.java:248)
at net.ucanaccess.jdbc.DefaultJackcessOpener.open(DefaultJackcessOpener.java:38)
at net.ucanaccess.jdbc.DBReference.<init>(DBReference.java:158)
at net.ucanaccess.jdbc.DBReferenceSingleton.loadReference(DBReferenceSingleton.java:57)
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:103)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at ex01.main(ex01.java:37)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.builder.CompareToBuilder
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 28 more
code to connect to database:
public class ex01 {
public static void main(String[] args) {
String url = "jdbc:ucanaccess://C:/Users/dave/My_WorkSpace/Eclipse_Workspaces/workspace-jsp/Database11.accdb";
Connection con;
Statement stmt;
String query = "Select * from user";
try {
// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
con = DriverManager.getConnection(url, "", "");
stmt = con.createStatement();
// Returns a ResultSet that contains the data produced by the query;
// never null
ResultSet rs = stmt.executeQuery(query);
System.out.println("User Data:");
System.out.println("FirstName\tLastName\tAge");
while (rs.next()) {
String fName = rs.getString("FirstName");
String lName = rs.getString("LastName");
int age = rs.getInt("age");
System.out.println(fName + "\t" + lName + "\t" + age);
}
stmt.close();
con.close();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
As you can see, jackcess 2.1.2 depends on commons-lang 2.6. The version you use (3.4) is not backward compatible.
Why do you have a JDBC driver for MySQL and for HSQLDB if your goal is to connect to MS Access?
This question already has answers here:
runtime error: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
(6 answers)
Closed 9 years ago.
I'm trying to run this program
import java.sql.*;
import java.io.*;
public class FirstExample
{
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "root";
static final String PASS = "pass";
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
try
{
//STEP 2: Register JDBC driver
Class.forName("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 title,duration,protocol,URL,thumbURL,favorite FROM Videos";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next())
{
//Retrieve by column name
String title = rs.getString("title");
String duration = rs.getString("duration");
String protocol = rs.getString("protocol");
String URL = rs.getString("URL");
String thumbURL = rs.getString("thumbURL");
String favorite = rs.getString("favorite");
//Display
System.out.println("Title:" + title);
System.out.println("Duration:" + duration);
System.out.println("Protocol:" + protocol);
System.out.println("URL:" + URL);
System.out.println("ThumbURL:" + thumbURL);
System.out.println("Favorite:" + favorite);
}
//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
}
System.out.println("Goodbye!");
}
}
But I'm getting the ClassNotFoundException
D:\XML Tests>javac FirstExample.java
D:\XML Tests>java FirstExample
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at FirstExample.main(FirstExample.java:21)
Goodbye!
Having consulted the numerous question available i.e setting the PATH system variable to the Connector directory, it still isnt working.
Any help please?
Add the jar containing the mysql driver class com.mysql.jdbc.Driver in the classpath.
Add MySQL driver jar to your project classpath and done.
The error is trying to tell you that it's not able to find the com.mysql.jdbc.Driver which is required when you are using MySql for data storage. So What you need to do is download the JConnector. And then import that jar file into your project classpath. Then you will not get the error.
I am trying to connect to a Netezza database using the JDBC driver and do a simple SELECT query. I have the nzjdbc.jar file in the lib folder in my project (using eclipse) and I am getting the following error.
java.lang.ClassNotFoundException: org.netezza.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Tests {
public static void main(String[] args)
{
String server = "myhost.com";
String port = "5480";
String dbName = "dbname";
String url = "jdbc:netezza://" + server + "/" + dbName ;
String user = "user";
String pwd = "pwd";
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("org.netezza.Driver");
System.out.println(" Connecting ... ");
conn = DriverManager.getConnection(url, user, pwd);
System.out.println(" Connected "+conn);
String sql = "SELECT COUNT(*) FROM TABLE";
st = conn.createStatement();
rs = st.executeQuery(sql);
if(rs.next()) {
System.out.println(rs.getString(1));
} else {
System.out.println(" No data found");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if( rs != null)
rs.close();
if( st!= null)
st.close();
if( conn != null)
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
In Eclipse you will need to add the jar to the libraries in your "Build path"
Eclipse documentation
Tutorial
Can any one help me how to run this code...
If I compile this code it complies successfully, But when I run class file throws
This is the stack trace for that exception :
Exception: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
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:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at ExportData.main(ExportData.java:13)
Here is the code :
import java.io.*;
import java.sql.*;
public class SampleMysql {
public static void main(String args[]) {
String Driver;
Statement stmt;
ResultSet rs;
Driver = "com.mysql.jdbc.Driver";
Connection con = null;
try {
Class.forName(Driver);
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/TempAttendance","root", password);
if(!con.isClosed()){
System.out.println("Successfully connected to MySQL DataBase \n");
stmt = con.createStatement();
String tablename = "Employee_Master";
String sql;
rs = stmt.executeQuery("select * from Employee_Master");
while(rs.next()) {
System.out.print(rs.getString("Name"));
}
}
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {
}
}
}
}
You should download and place your driver jar (mysql jar) file in your class path
Documentation
Did you download Connector/J
MySQL Connector/J is the official JDBC driver for MySQL.
MySQL driver class (com.mysql.jdbc.Driver) is not available.
Due to that you are getting Exception :com.mysql.jdbc.Driver error.
Include mysql-connector-java-5.0.8-bin.jar Jar file into WEB-INF/lib folder, which resolve this issue.
Hi All
I am trying to connect a data base. below i have given the code. I am able to connect to data base but unable to connect 2nd time if difference between 1st time and 2nd time is greater then "wait time out" of mysql data base.
I am using mysql data base. I am getting "Communications link failure" problem
wait_timeout is 10 sec (for convenience) it is 8 hour for my DB
I am giving you code
public class DatabaseManager {
private static Connection jConn;
private static DatabaseManager manager;
public Boolean getUser(){
Statement jStmt = null;
ResultSet rs = null;
try {
String query = "SELECT * FROM USER ";
System.out.println(query);
jStmt = jConn.createStatement();
rs = jStmt.executeQuery(query);
while (rs.next()) {
}
}catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public static synchronized DatabaseManager getInstance() {
if (manager == null) {
try {
manager = initialize();
} catch (DatabaseInitializationException e) {
// e.printStackTrace();
// throw new RuntimeException("Database Initialization
// Exception");
}
}
return manager;
}
private static DatabaseManager initialize()
throws DatabaseInitializationException {
try {
Class.forName(serverSrv.readPropertyValue("Srver_Path",
"DBdriver"));
} catch (ClassNotFoundException e) {
throw new DatabaseInitializationException(e.getMessage());
}
try {
jConn = DriverManager.getConnection("DB_URL","user","password");
System.out.println("Excecuted initialize() for Database ");
} catch (SQLException e) {
throw new DatabaseInitializationException(e.getMessage());
}
return new DatabaseManager();
}
}
AND I am testing like
public static void main(String[] args) {
long st = System.currentTimeMillis();
long end ;
DatabaseManager dm = DatabaseManager.getInstance();
if( dm.getUser() )
System.out.println("success");
else
System.out.println("failed..");
do{
end = System.currentTimeMillis();
}while( (end-st)<12*1000 );
if( dm.getUser() )
System.out.println("success");
else
System.out.println("failed..");
}
and it is giving exception like
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Last packet sent to the server was 0 ms ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2873)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2763)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3299)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1837)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1961)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2537)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2466)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1383)
at mypackage.db.DatabaseManager.getUser(DatabaseManager.java:127)
at mypackage.test.Test.main(Test.java:23)
Caused by: java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:113)
at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:160)
at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:188)
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2329)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2774)
Perhaps you should close the ResultSet as well as Statement.
This link has some tips on doing this correctly.
Your problem is that you are trying to reuse jConn which closes automatically after a timeout. So when you try and use it again an exception is thrown. Depending on what you are trying to do i would suggest (for simplicity) ..
Closing jConn by typeing jConn.close();
Then When you need to use the db again reconnect using jConn = DriverManager.getConnection("DB_URL","user","password");
Check your connection time out settings.