我尝试使用 JDBC 运行一些查询,但不断收到此错误:
Exception in thread "main" java.lang.IllegalStateException: error
at com.mycompany.app.App.writer(App.java:195)
at com.mycompany.app.App.main(App.java:19)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname
这是我的代码的相关部分:
public class App {
writer();
}
public static void writer() {
String url = "jdbc:mysql://localhost:3306/dbname
String username = "root";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, username, password)) {
Statement st = connection.createStatement();
ResultSet r= st.executeQuery("insert query here");
} catch (SQLException e) {
throw new IllegalStateException("error");
}
}
}
当我通过 Intellij Idea 运行它时,它可以工作,但我需要它在运行 Centos 的服务器上运行。
我尝试使用以下命令运行它:
javac -cp "filepath/mysql-connector-java-5.1.35-bin.jar" App.java
java -cp ".filepath/mysql-connector-java-5.1.35-bin.jar" App
我尝试过使用maven运行它,包括
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
在 pom.xml 中仍然得到相同的错误
我在网上浏览了很多文章(以及堆栈问题),但仍然找不到解决方案。
服务器运行CentoOS 6.6,数据库在本地运行。
我正在使用:
java版本“1.8.0_45” Java(TM) SE 运行时环境(版本 1.8.0_45-b14) Java HotSpot(TM) 64 位服务器 VM(内部版本 25.45-b02,混合模式)
最佳答案
类 Unix 操作系统上的类路径条目必须用 :
分隔。在 .
(表示当前目录)和 jar 路径之间添加 :
:
java -cp .:filepath/mysql-connector-java-5.1.35-bin.jar App
关于java.sql.SQLException : No suitable driver found for jdbc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30853999/