简体   繁体   English

无法连接到MySQL数据库:找不到合适的驱动程序

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

I'm having some troubles with java and jdbc. 我在使用java和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: 特别是,尽管我的代码可以完美地在NetBeans项目中正常工作,但是当我尝试在终端或ubuntu vps(这是我需要它的地方)上执行它时,我总是会遇到此异常:

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; 首先,是第一件事:是的,我正在将jdbc .jar添加到execute命令和compile命令中; 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. 但我总是收到ClassNotFoundException: com.mysql.jdbc.Driver异常我正在使用的.jar与NetBeans项目中使用的.jar完全相同,所以我知道我有正确的选择,甚至可以从官方网站不会改变任何事情。 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. 我也尝试过切换到postgresql(是的,我没有忘记更改URL),但无济于事,它仍然找不到驱动程序。 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); javac *.java <-cp mysql-connector-java-5.1.41-bin.jar > (<>括号表示我尝试使用和不指定类路径进行编译);

java TAW -cp mysql-connector-java-5.1.41-bin.jar , 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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