ClassNotFoundException java

时间:2014-08-26 18:48:06

标签: java mysql classnotfoundexception

我对Class Not Found Exception有疑问。我已经在我的文件中添加了所有的罐子,但我似乎无法使它工作。我在我的项目中添加了mysql-connector.jar。有人知道如何做对吗?

try {
    String driverName = "com.mysql.jdbc.Driver";
    Class.forName(driverName);

    String serverName = "localhost";
    String mydatabase = "UFRJSocial";
    String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
    String username = "root";
    String password = "";

    connection = DriverManager.getConnection(url, username, password);

    if (connection != null) {
        status = ("STATUS--->Connected!");
    } else {
        status = ("STATUS--->The connection failed");
    }

    return connection;

} catch (ClassNotFoundException e) {
    System.out.println("The specified driver was nor found");
    //THIS IS THE LINE THAT MY CONSOLE IS SHOWING
    return null;
} catch (SQLException e) {
    System.out.println("it was not possible to connect to the database.");
    return null;
}

2 个答案:

答案 0 :(得分:0)

请看一下这段代码:

enter code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import app.dao.connector.DatabaseManager;

public class MySQLDatabaseManager implements DatabaseManager{
@Override
public Connection getConnection() {
    final String USER_NAME  ="root";
    final String PASSWORD = "1234";
    final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    final String JDBC_URL = "jdbc:mysql://localhost:3306/inventory system";

    Connection conn = null;

    try{
        Class.forName(JDBC_DRIVER);
        conn = DriverManager.getConnection(JDBC_URL, USER_NAME, PASSWORD);
    }catch(ClassNotFoundException e){
        e.printStackTrace();
    }catch(SQLException e){
        e.printStackTrace();
    }
    return conn;
    }

正如您所看到的,我尝试在try和catch块之外声明所有变量。声明 JDBC_URL 指定数据库。

答案 1 :(得分:0)

我设法让它发挥作用。它缺少Web-INF文件夹中的mysql.jar文件。