JDBC找不到合适的驱动程序

时间:2014-04-05 15:20:23

标签: java mysql sql jdbc

我正在尝试用Java创建一个自定义的MySQL类,但是我得到了一些例外,这是我的代码:

MySQL.java:

package evo.common;

import java.sql.*;

public class MySQL {

private static String hostname;
private static String username;
private static String password;
private static String database;

public MySQL(String host, String user, String pass, String db)
{
    hostname = host;
    username = user;
    password = pass;
    database = db;
}

public static void Error(Exception ex)
{
    System.out.println("Fatal Error: "+ex.getMessage());
}

public static void SQLError(SQLException ex)
{
    System.out.println("Fatal SQL Error: "+ex.getMessage());
}

private static Connection connect()
{
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch(Exception e){
        Error(e);
    }

    String url = "jdbc:mysql://"+hostname+":3306/"+database;
    Connection conn = null;

    try {
        conn = DriverManager.getConnection(url, username, password);
    } catch(SQLException ex){
        SQLError(ex);
    }

    return conn;
}

public static ResultSet result(String query)
{
    Connection conn = connect();
    PreparedStatement pst = null;
    ResultSet rs = null;

    try
    {
        pst = conn.prepareStatement(query);
        rs = pst.executeQuery();
    } catch(SQLException ex){
        SQLError(ex);
    }

    return rs;
}

public static void main(String args[]){}

}

Test.java:

package evo.common;
import java.sql.*;
public class Test {
public static void main(String args[])
{
    MySQL mysql = new MySQL("localhost", "root", "******", "souljaz");

    ResultSet res = mysql.result("SELECT * FROM users");
}

}

当我运行Test时,我在控制台中收到以下错误消息:

Fatal Error: com.mysql.jdbc.Driver
Fatal SQL Error: No suitable driver found for jdbc:mysql://localhost:3306/souljaz
Exception in thread "main" java.lang.NullPointerException
at evo.common.MySQL.result(MySQL.java:58)
at evo.common.Test.main(Test.java:8)

我对Java很陌生,所以非常感谢。感谢。

1 个答案:

答案 0 :(得分:2)

下载最新版本的Connector/J并将其包含在您的Classpath中。如果您使用的是IDE,那么只需将jar包含在引用的库中即可。如果您手动完成所有操作,请参阅此official guide

java -cp "bin;lib/mysql-connector-java-5.1.30-bin" evo.common.Test

<强>更新

在Eclipse中:在Package Explorer中右键单击您的项目,然后:

Properties -> Java Build Path -> Add JARS... (if lib is in the project)
                              or Add External JARS... (if it is external)