java.lang.ClassNotFoundException: org.netezza.Driver - java

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

Related

Issue with question mark in jdbc PreparedStatement [duplicate]

This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 2 months ago.
I've gone through the internet back and forth and found no solution to my problem.
I am trying to use parameter binding with jdbc for querying a mysql table, but it keeps reporting syntax error for the question mark in my statement.
Here is my class:
package todoList_;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
public class testBinding {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/TODO?useJvmCharsetConverters=true";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String args[]) {
// TODO Auto-generated method stub
Connection conn = null;
Statement stmt = null;
HashMap<Integer, String> list = new HashMap<Integer, String>();
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 * from todos where `id` = ?";
PreparedStatement preparedStatement1 = conn.prepareStatement(sql);
preparedStatement1.setInt(1, 0);
ResultSet rs = preparedStatement1.executeQuery(sql);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
list.put(rs.getInt("id"), rs.getString("name"));
}
// 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
}
}
And here is my Log:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
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:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2618)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1557)
at todoList_.testBinding.main(testBinding.java:41)
I am using mysql-connector-java-5.1.18-bin.jar, that I have copied to WebContent/WEB-INF/lib and added to the Build Path of the project.
I use Eclipse.
Could you please advise?
write
ResultSet rs = preparedStatement1.executeQuery();
instead of
ResultSet rs = preparedStatement1.executeQuery(sql);

How to connect MS Access database with Java 8?

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?

ClassNotFoundException when running sample MySQL code in eclipse

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

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver - Not Working [duplicate]

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.

class not found exception even after everything seems right

I am working on simple connection between Java and MySQL using MySQL Connector J on Windows 8.
Below is the code that i am trying to execute:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Version {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/test";
String user = "testuser";
String password = "test623";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
Compile:
javac Version.java (goes without error and generates class file)
Execute:
java -cp "path to mysql connector java jar file" Version
Execution Result:
Exception in thread "main" java.lang.NoClassDefFoundError: Version
Caused by: java.lang.ClassNotFoundException: Version
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)
Could not find the main class: Version. Program will exit.
Any idea where am i wrong?
You have to add the directory containing Version.class to the classpath as well as the mysql-connector-jar.
If you don't add a classpath-parameter to the invokation java will look for class-files in the current directory by default. If you add a classpath, java will only search the mentioned jar-files/directories for class files, current directory has to be explicitly included as .

Categories