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 .
Related
I am developing a simple login form but got error while running one Tomcat server.
Below is the stack trace :
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
at jav.com.utility.Utility.getConnection(Utility.java:23)
at jav.com.dao.daoLogin.<init>(daoLogin.java:12)
at jav.com.controller.conrollerServletLogin.<init>(conrollerServletLogin.java:23)
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 java.lang.Class.newInstance(Unknown Source)
db.properties file
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/pra
user=root
password=root
Utility.java
package jav.com.utility;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Utility {
private static Connection connection;
public static Connection getConnection() {
if (connection != null) {
return connection;
} else {
try {
Properties prop = new Properties();
// file input output this code read db.properties file from location src
InputStream inputStream = Utility.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
// String driver="com.mysql.jdbc.Driver";
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
I tried to solve but I am getting error like 404 and 500 .
Hi I am trying to connect with Cassandra using jdbc driver. I am getting the following exception.
java.sql.SQLNonTransientConnectionException: Connection url must specify a host, e.g., jdbc:cassandra://localhost:9170/Keyspace1
at org.apache.cassandra.cql.jdbc.Utils.parseURL(Utils.java:190)
at org.apache.cassandra.cql.jdbc.CassandraDriver.connect(CassandraDriver.java:85)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.sub.cas.CqlJdbcTestBasic.main(CqlJdbcTestBasic.java:14)
My cassandra server is running fine and can be accessed from cql shell in windows 10 OS.
This is the java class that I have written.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CqlJdbcTestBasic {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra:/root/root#localhost:9160/hr");
String query = "SELECT empid, emp_first, emp_last FROM User WHERE empid = 1";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("empid"));
System.out.println(result.getString("emp_first"));
System.out.println(result.getString("emp_last"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
con = null;
}
}
}
}
I have gathered my jars from this url :: https://code.google.com/archive/a/apache-extras.org/p/cassandra-jdbc. Unable to find any possible solution. Please help.
Please, check if you have two slashes before your user name. According to
http://www.dbschema.com/cassandra-jdbc-driver.html
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.