简体   繁体   中英

Can't connect to MySQL database: No suitable driver found

I'm having some troubles with java and jdbc. In particular, while my code perfectly works in a NetBeans project, when i try to execute it on a terminal or on my ubuntu vps (which is where i need it to work) i always get this exception:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/quakes

First thing first: yes, i'm adding the jdbc .jar to the execute command and the compile command; Yes, i've even tried to add

Class.forName("com.mysql.jdbc.Driver"); ,

but I always get a ClassNotFoundException: com.mysql.jdbc.Driver exception The .jar i'm using is the exact same that i use in the NetBeans project, so i know i have the right thing, and even downloading it again from the official site won't change a thing. Yes, the database exists, and the result doesn't change if i try to connect to another db. I also tried switching to postgresql (yes, i didn't forget to change the url), but to no avail, it still can't find the driver. With this, i'm guessing that the actual error is in the compile/execute commands, but even them should be ok:

javac *.java <-cp mysql-connector-java-5.1.41-bin.jar > (the <> parenthesis means that i tried compiling with and without specifying the classpath);

java TAW -cp mysql-connector-java-5.1.41-bin.jar ,

In case you want to see it, here's the method that tries to connect to the database:

public Connection getConnection() throws SQLException {
    if (conn == null) {
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+
        this.dbname,this.user,this.pass);
    }
    return conn;
}

Does anyone have any idea on why this happens?

您需要将java的classpath选项放在主类的名称之前,否则将其视为程序参数:

java -cp mysql-connector-java-5.1.41-bin.jar;. TAW

You can use this method step by step to create connetion.

it is an example connectivity:

  Class.forName("com.mysql.jdbc.Driver");
                    // Setup the connection with the DB
                    connect = DriverManager
                                    .getConnection("jdbc:mysql://localhost/feedback?"
                                                    + "user=sqluser&password=sqluserpw");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM