Java program and mySQL connectivity issue: No suit

2019-07-31 08:42发布

问题:

I've been having a problem with mySQL database connectivity. I'm getting an error:

No suitable driver found for jdbc:mysql://127.0.0.1/sakila.

I have installed mySQL workbench, and have the driver from here http://dev.mysql.com/downloads/connector/j/

I have saved mysql-connector-java-5.1.18-bin and set the classpath to

C:\Program Files\Java\jre7\lib\mysql-connector-java-5.1.18-bin;

and started the mysql workbench where the database is found.

The code I am using is as follows: Which I am sure works, as I've asked a friend to test it form me. Unfortunately, we are developing on different platforms and could not instruct me as to how to fix this error. Has anyone an idea on how I can fix this?

public class Version {

public static void main(String[] args) {

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    String url = "jdbc:mysql://127.0.0.1/sakila";
    //String url = "jdbc:mysql://localhost:3306/sakila";
    String user = "root";
    String password = "root";


    try {


        con = DriverManager.getConnection(url, user, password);
        st = con.createStatement();
        rs = st.executeQuery("select * from actor;");

        System.out.println("test");

        if (rs.next()) {
            System.out.println(rs.getString(1));
        }

    } catch (Exception ex) {
        System.out.println(ex);
}
}

}

EDIT: Problem sovled. Did not have .jar appended to the end of the bin file, which is necessary.

回答1:

Plz add the following

String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();

right before the line "con = DriverManager.getConnection(url, user, password);"

All you need to do is load the driver class before getting the connection from the drivermanager.



回答2:

You need to instantiate the driver before calling the getConnection :

String pdriver = "com.mysql.jdbc.Driver";
Class.forName(pdriver).newInstance();


回答3:

You need to place the connector jar file to your classpath or ...\jre1.6.0\lib\ext

Classpath is the one you should favor instead of the latter


回答4:

You need to add the MySQL connecter library jar file to the classpath, rather than the directory where it is contained.

Are you not using an IDE like Netbeans or Eclipse? Setting up a command line development environment in Windows is not hard but it's not trivial either