Using MySQL and database and having ClassNotFoundException - java

I have these two classes in my database package:(DBManager and TaskManager class)
and I create a new object in my main frame which is in the other package and I also imported the database package for my main frame and I call addBirth() on my object,and I want to insert these arguments in my table="birthsql" in MySQL but I found this exception and also was written "SERVER = NULL".
creating an object--> TaskManager tm = new TaskManager();
calling addBirth() method on my object-->, tm.addBirth(3, "Neda","Rahmani", "Mansour", "Sima","December","Tehran");
My TaskManager class:
public class TaskManager {
private int BirthID = 2;
Logger logger = Logger.getLogger(this.getClass().getName());
private Connection conn = DBManager.getConnection();
public int getID()
{
return BirthID++;
}
public void addBirth(int BirthID, String name, String family, String fatherName, String motherName, String DateOfBirth, String PlaceOfBirth) {
try {
Statement stm = conn.createStatement();
stm.executeUpdate("INSERT INTO birthsql (name," + "family," + "fatherName," + "motherName," + "DateOfBirth, " + "PlaceOfBirth)" + "VALUES (" + BirthID + ", '" + name + "', '" + family + "', '" + fatherName + "', '" + DateOfBirth + "', '" + PlaceOfBirth + "')");
} catch (SQLException ex) {
Logger.getLogger(TaskManager.class.getName()).log(Level.SEVERE, null, ex);
}
}}
My DBManager class:
public class DBManager {
private static Logger log = Logger.getLogger(DBManager.class.getName());
private static Connection connection = null;
private final static String DB_URL = "jdbc:mysql://localhost:3306/assignment_2";
private final static String DB_USERID = "root";
private final static String DB_PASSWORD = "123";
public static Connection getConnection()
{
if (connection == null)
{
try {
/* Your code here */
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(DB_URL, DB_USERID, DB_PASSWORD);
} catch (SQLException ex) {
Logger.Dec 10, 2009 6:44:05 AM database.DBManager getConnection
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
return connection;
}}
Stacktrace:
Dec 10, 2009 6:44:05 AM database.DBManager getConnection
SEVERE: null
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at database.DBManager.getConnection(DBManager.java:32)
at database.TaskManager.<init>(TaskManager.java:21)
at adminFrame.AdminFrame.<init>(AdminFrame.java:29)
at adminFrame.AdminFrame$4.run(AdminFrame.java:239)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at database.TaskManager.addBirth(TaskManager.java:30)
at adminFrame.AdminFrame.<init>(AdminFrame.java:46)
at adminFrame.AdminFrame$4.run(AdminFrame.java:239)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121

Just because your code compiles and can start running does not mean you have all the required stuff on your classpath. The code compiles because you're using the basic JDBC interfaces that are built into the Java language distribution, but when you run, JDBC tries to instantiate the MySQL specific connectors and can't (the Class.forName call). It looks like you've got a jar missing on your classpath. You can get one here:
http://dev.mysql.com/downloads/connector/j/5.1.html

I added Driver jar on my classpath
You thought you did it properly, but the JVM is telling you that you did not.
How did you do it? The right way is not a CLASSPATH environment variable. The JVM, IDEs and app servers all ignore it.
The right thing to do depends on how you're running your app.
If you're running on the command line, use the -cp option and provide the full path to the MySQL Connector-J JAR.
If you're using an IDE like IntelliJ or Eclipse, you'll have to know how to add the MySQL driver JAR to the build lib path.
If you're creating a web app, you should either put it in your app's WEB-INF/lib directory or, better yet, the /lib directory for your app server.
Most of all, believe the error message. You did it incorrectly. Figure out the right way.
UPDATE: Looks like a duplicate of 1878405.

Do you have the MySQL JDBC driver jar on your classpath?

If you have the MySQL JARs, make sure they're in the classpath. If you don't, download them here.

You can't write Java without knowing how to set CLASSPATH.
If you're using an IDE like IntelliJ or Eclipse, you'll have to add the JAR to your build library path.
If you're using an app server, you should put it in your WEB-INF/lib or, better yet, the /lib directory for your app server.

Related

Jar file not connecting to existing database

I have a JAR file that doesn't connect to the database even though it connects just fine in the IDE. I'm stuck and I don't know where to go from here. I am using Java 8 in IntelliJ trying to run SQLite.
Here is the code for the Database class.
private static Connection connection = null;
private static boolean connected = false;
static void connect() {
String driver = "org.sqlite.JDBC";
String db = "schedulerDB";
String path = "lib\\";
String url = "jdbc:sqlite:";
try {
Class.forName(driver);
connection = DriverManager.getConnection(url + path + db);
printInfo("Connected to database : " + db);
connected = true;
} catch (SQLException e) {
printError(1100, "Could not connect to database", e);
} catch (ClassNotFoundException e) {
printError(1101, "Driver not found error", e);
}
}
When I run the JAR file in the terminal, I get:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
Please help me.
Added e.printStackTrace(); as requested:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
at org.sqlite.core.DB.newSQLException(DB.java:941)
at org.sqlite.core.DB.newSQLException(DB.java:953)
at org.sqlite.core.DB.throwex(DB.java:918)
at org.sqlite.core.NativeDB.prepare_utf8(Native Method)
at org.sqlite.core.NativeDB.prepare(NativeDB.java:134)
at org.sqlite.core.DB.prepare(DB.java:257)
at org.sqlite.jdbc3.JDBC3Statement.execute(JDBC3Statement.java:52)
at scheduler.Database.query(Database.java:337)
at scheduler.User.buildList(User.java:42)
at scheduler.User.<clinit>(User.java:85)
at scheduler.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Unknown Source)
Change the value of url to
url = "jdbc:sqlite::resource:"
Your exception is actually caused by a MalformedURLException. The reason you are getting this is because lib\schedulerDB is not a valid URL.
URLs must use forward slashes (/), on all systems—even Windows. This is a requirement of the URI specification itself. (A URL is a type of URI, so every URL must conform to the rules of a URI.)
Making your URL valid should do the trick:
String path = "lib/";

Java Program compile and run in command prompt successfully but not in myeclips?

I'm learning jdbc and working with Oracle database by writing this simple code. The IDE i'm using is MyEclips. But the problem is when I compile and run this program in command prompt it works properly but when I try to compile and run this program in my IDE i.e. MyEclips it through an error message:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
import java.sql.*;
class OracleCon{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = null;
String URL = "jdbc:oracle:thin:#localhost:1521:xe";
String UN = "HR";
String PASS = "12345";
con = DriverManager.getConnection(URL,UN,PASS);
Statement stmt = con.createStatement();
String sql = "SELECT * FROM EMPLOYEES";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I also set the class path in Environment variable.Environment variable snippet
Verify that the name of the requested class is correct and that the appropriate .jar file exists in your classpath. If not, you must explicitly add it to your application’s classpath.
In case the specified .jar file exists in your classpath then, your application’s classpath is getting overriden and you must find the exact classpath used by your application.
In case the exception is caused by a third party class, you must identify the class that throws the exception and then, add the missing .jar files in your classpath.

jdbc mysql driver not found after deploying

I have developed a REST application using jersey where to connect to database(mysql) I use jdbc connection. Following is the configuration.
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/DBNAME";
static final String USER = "root";
static final String PASS = "********";
public List<Item> getAll() {
List<Item> results = new ArrayList<>();
try (Connection conn = (Connection) DriverManager.getConnection(DB_URL,
USER, PASS);
Statement stmt = (Statement) conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM items");) {
while (rs.next()) {
// Retrieve by column name
System.out.println(rs.getInt("ID"));
System.out.println(rs.getString("FormerCode"));
System.out.println(rs.getString("NewCode"));
results.add(new Item(rs.getInt("ID"), rs
.getString("FormerCode"), rs.getString("NewCode")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return results;
}
All things works when I deploy via Eclipse. But when I create the war file and deploy it manually on tomcat server it gets the exception saying there is no suitable driver.
No suitable driver found for 'jdbc:mysql://localhost:3306/DBNAME
I have included the mysql-connector jar files in both WEB-INF/lib folder and TOMCAT_HOME/lib folder. But I am still getting this error. Server is running on Ubuntu Server 14.04.
Paths where jar is added.
src/main/webapp/WEB-INF/lib
usr/share/tomcat7/lib
What seems to be the problem hence I have added the jar files to necessary locations??
Sometimes java class failed to pick driver's(mysql java connector jar file) path from lib folder. To remove this issue you can extract connector jar in following directory of your project.
src/main/webapp/WEB-INF/classes
OR
You may also compile the java file with classpath reference of mysql_java_connector.jar.
The answer was when using a DriverManager interface to create a JDBC Connection, always create an instance of your JDBC driver first in order to load it into your Classloader.
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
Thanks all.

ClassNotFoundException for com.microsoft.sqlserver.jdbc.SQLServerDriver

This is an issue that has come up before on SO, and I'm sure seasoned Java devs are tired of telling newbies howto set the classpath. That said, I've tried setting the classpath via environment variable and with the -cp option, with no success.
I'm using the sample applications that are bundled with the SQLServer JDBC driver. I'm running Ubuntu 14.10. I compile the app on the command line:
javac -cp .:/path/to/sqljdbc42.jar connectURL.java
and the run it:
java connectURL
which gets me the familiar ClassNotFoundException:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
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:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
at connectURL.main(connectURL.java:42)
I haven't modified the sample class file, but I'm including it here for completeness:
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM Person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
The path to the SQL JDBC .jar is definitely correct. If I add import com.microsoft.sqlserver.jdbc.SQLServerDriver; to the class file I don't get any complaints when compiling, but still get the ClassNotFoundException at runtime.
I've read elsewhere that newer versions of the JDBC don't need you to load drivers via Class.forName, but if I remove that line then I get, predictably, java.sql.SQLException: No suitable driver found.
What am I doing wrong? I'm sure the .jar is being loaded and the class is being found, because if I try e.g. import com.microsoft.sqlserver.jdbc.SomeNonExistentClass; I get:
connectURL.java:2: error: cannot find symbol
My Java details:
$ java -version
java version "1.7.0_79"
OpenJDK Runtime Environment (IcedTea 2.5.5) (7u79-2.5.5-0ubuntu0.14.10.2)
OpenJDK 64-Bit Server VM (build 24.79-b02, mixed mode)
You're halfway there. You include the JDBC JAR on your classpath when you compile, but you also need to include it on your classpath when you execute it as well:
java -cp .:/path/to/sqljdbc42.jar connectURL

"ClassNotFoundException: com.mysql.jdbc.Driver"

I’m new using IntelliJ 13 and I have a problem on connection to MySQL. I’m using the code as below and this code I learn from tutorials Manage Your Database Scheme with IntelliJ IDEA 12.
public class App {
public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
public static final String JDBC_URL = "jdbc:mysql://localhost/sample";
public static final String JDBC_USER = "root";
public static final String JDBC_PASSWORD = "";
public static void main (String[] args) throws SQLException, ClassNotFoundException {
Statement statement = null;
try{
Class.forName(JDBC_DRIVER);
Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select id, firstname, lastname, email " +
"from customer");
System.out.println("First name\tLast name\tEmail");
int count = 0;
while (resultSet.next()){
String firstname = resultSet.getString("firstname");
String lastname = resultSet.getString("lastname");
String email = resultSet.getString("email");
System.out.printf("%s\t%s\t%s%n", firstname, lastname, email);
count++;
}
System.out.println("--");
System.out.println(MessageFormat.format("Rows: {0}", count));
} finally {
if(statement != null){
statement.close();
}
}
}
}
I have tried many solution based on this issue on https://stackoverflow.com/ but nothing can solved my problem.
It give error message like this
Connection to MySQL – sample#localhost failed: Exception in thread “main” java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
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:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at com.intellij.persistence.database.console.RemoteJdbcServer.main(RemoteJdbcServer.java:15)
I've followed this as well to solve my problem, but nothing works to me even the problem is same.
http://nixmash.com/java/classnotfoundexception-com-mysql-jdbc-driver-fix-in-intellij-idea/. Actually, I want to create database using MySQL on IntelliJ 13 but the connection to MySQL is failed. I have tried to solve this problem with putting mysql-connector-java-5.1.26-bin.jar in project structure, but it's not work for me. I don't know how to solve this problem? I hope some experts on this issue will help me some ways to solve this problem.
I cannot use the comment, I don't know why. So I reply the answer here. Ashish: I already download the jar files, but I don't know where to put that files. Do you have idea?
You need to download jar containing com.mysql.jdbc.Driver .
So you can Download jar from here and then set your classpath.

Categories