Java program and mySQL connectivity issue: No suitable driver found

一笑奈何 提交于 2020-01-11 10:26:12

问题


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:


You need to instantiate the driver before calling the getConnection :

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



回答2:


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.




回答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



来源:https://stackoverflow.com/questions/9777880/java-program-and-mysql-connectivity-issue-no-suitable-driver-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!