Java JDBC连接没有发生

Java JDBC连接没有发生,java,mysql,eclipse,ubuntu,jdbc,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 (SQLExc

下面是我用于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)
您能告诉我如何获取JDBCURL吗


我正在ubuntu 14.04中使用eclipsemars,请先加载驱动程序:

Class.forName("com.mysql.jdbc.driver");
这是你写的

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);
}
请查收

让我们快速了解一下如何使用此新功能加载 JDBC驱动程序管理器。下面的清单显示了 我们通常使用加载JDBC驱动程序。让我们假设我们需要 连接到ApacheDerby数据库,因为我们将在 本文后面解释的示例应用程序:

 Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
    Connection conn =
        DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
但是在JDBC4.0中,我们不需要Class.forName行。我们可以 只需调用getConnection即可获得数据库连接

请注意,这是用于在单机中获取数据库连接 模式如果您使用某种类型的数据库连接池来管理 连接,那么代码就不同了

出现这种异常的原因很多,没有找到适合jdbc的驱动程序:类似mysql

您的JDBC URL可能是错误的。 ClassPath/BuildPath/Lib文件夹缺少连接器jar。 司机信息是错误的。
只需将com.mysql.jdbc.Driver添加到程序文件中的lib文件夹中。

如果您使用的是netbeans,右键单击project->properties->libraries->add library并选择MySQL JDBC驱动程序

您的类路径中是否有MySQL jar文件?只需加载驱动程序first class.forname com.MySQL.JDBC.Driver就可以了。您更正的代码已经过时:不再需要使用class.forname,您甚至可以通过引用的文本来确认它,OP正确地使用了try-with-resources,假设他们不想对连接做任何其他事情,您的代码通过删除try-with-resources来撤销连接。自从Java 6/JDBC 4+兼容JDBC 4的驱动程序以来,使用Class.forName就不再是必需的了