【问题标题】:Why is it not connecting to my database? Java JBDC,为什么它没有连接到我的数据库? Java JDBC,
【发布时间】:2016-06-27 09:47:32
【问题描述】:

错误是“异常:无效的数据库地址:jdbc:mysql://localhost:3306/library?user=root&password=myPassword” 我正在使用 MySQL 数据库并且是这方面的初学者,所以我有点困惑。我在 MySQL 中的数据库名称是“library”....所以有人能指出我正确的方向吗?

import java.sql.*;
public class connectToMySQL {


public static void main(String[] args) {
     Connection con = null;
        try {

          con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/library?user=root&password=myPassword");
          System.out.println("Connected with the database!");

}
        catch (Exception e) {
            System.err.println("Exception: "+e.getMessage());

}
}
}

【问题讨论】:

  • 您需要注册您的数据库驱动程序。类似Class.forName("com.mysql.jdbc.Driver");
  • @user1875195 自 2007 年以来没有。

标签: java jdbc


【解决方案1】:

这不是一个有效的数据库 URL。改变这个

con = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/library?user=root&password=myPassword");

使用DriverManager.getConnection(String, String, String)。类似的东西

con = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/library", "root", "myPassword");

另外,您可以使用try-with-resources close statement。喜欢,

try (Connection con = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/library", "root", "myPassword")) {

【讨论】:

    猜你喜欢
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2016-03-14
    • 2017-01-24
    • 2018-05-12
    • 2018-05-10
    • 2016-01-12
    相关资源
    最近更新 更多