JDBC No suitable driver found

2019-07-24 17:42发布

问题:

I'm trying to make a custom MySQL class in Java but I'm getting a few exceptions, here's my code:

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");
}

}

When I run Test I get these error messages in the console:

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)

I'm quite new to Java so help appreciated. thanks.

回答1:

Download the lastest version of Connector/J and included it in your Classpath. If you are using an IDE this is only a matter of including the jar in your referenced libraries. If you are doing everything by hand, refer to this official guide:

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

Update:

In Eclipse: Right click your project in Package Explorer, then:

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