JDBC连接没有发生

时间:2015-09-03 06:33:07

标签: java mysql eclipse ubuntu jdbc

以下是我用于jdbc连接的代码

String dbUrl="jdbc:mysql://localhost:3306/mysql";
String user= "kumar";
String pwd="ratiol";

try (Connection connection = DriverManager.getConnection(dbUrl, user, pwd)) {
    System.out.println("Database connected!");
} catch (SQLException e) {
    throw new IllegalStateException("Cannot connect the database!", e);
}

但我收到的错误如下 -

Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
    at jdbcConnection.Jdbcdemo.main(Jdbcdemo.java:22)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mysql
    at java.sql.DriverManager.getConnection(DriverManager.java:596)
    at java.sql.DriverManager.getConnection(DriverManager.java:215)
    at jdbcConnection.Jdbcdemo.main(Jdbcdemo.java:19)

请告诉我如何获取jdbc网址?

我在ubuntu 14.04中使用eclipse(mars)

4 个答案:

答案 0 :(得分:1)

如果您使用netbeans,请右键单击项目 - >属性 - > libraries - >添加库并选择MySQL JDBC Driver

答案 1 :(得分:0)

这就是你写的

try (Connection connection = DriverManager.getConnection(dbUrl, user, pwd)) {
    System.out.println("Database connected!");
} catch (SQLException e) {
    throw new IllegalStateException("Cannot connect the database!", e);
}

就像这样:

Connection con = null;
try {
    //registering the jdbc driver here, your string to use 
    //here depends on what driver you are using.
    Class.forName("something.jdbc.driver.YourFubarDriver");   
    Connection connection = DriverManager.getConnection(dbUrl, user, pwd)
} catch (SQLException e) {
    throw new RuntimeException(e);
}

请检查Class.forName not more needed when using JDBC v.4

  

让我们快速了解一下如何使用这个新功能来加载   JDBC驱动程序管理器以下清单显示了示例代码   我们通常用来加载JDBC驱动程序。让我们假设我们需要   连接到Apache Derby数据库,因为我们将使用它   示例应用程序在文章后面解释:

 Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
    Connection conn =
        DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
     

但是在JDBC 4.0中,我们不需要Class.forName()行。我们可以   只需调用getConnection()即可获得数据库连接。

     

请注意,这是为了在独立中获取数据库连接   模式。如果使用某种类型的数据库连接池进行管理   连接,然后代码会有所不同。

有很多理由需要No suitable driver found for jdbc:mysql例外

  1. 您的JDBC URL可能有误。
  2. ClassPath / BuildPath / Lib文件夹缺少连接器jar。
  3. 驱动程序信息错误。

答案 2 :(得分:0)

只需将com.mysql.jdbc.Driver添加到程序文件中的lib文件夹中。

答案 3 :(得分:-3)

首先加载驱动程序:

Class.forName("com.mysql.jdbc.driver");