java.sql.SQLException:没有为jdbc找到合适的驱动程序

时间:2015-06-15 20:01:59

标签: java mysql maven jdbc centos

我正在尝试使用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,混合模式)

3 个答案:

答案 0 :(得分:2)

类Unix操作系统上类路径上的条目必须用UriComponentsBuilder分隔。在:(表示当前目录)和jar的路径之间添加:

.

答案 1 :(得分:0)

或者,您可以将mysql-connector-java-5.1.35-bin.jar放在以下目录中 -

JAVA_HOME/jre/lib/ext 

如果您将jar放在此目录中,则无需使用命令将其添加到classpath

答案 2 :(得分:0)

您可以尝试使用class.forName("qualified name of driver class")加载驱动程序类。如果您没有面对maven的类路径问题,这应该可以解决问题。看看at this在哪里  索引标记已从pom中删除并且有效。

相关问题