为什么它没有连接到我的数据库? Java JBDC,

时间:2016-03-12 00:30:04

标签: java jdbc

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

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());

}
}
}

1 个答案:

答案 0 :(得分:2)

这不是有效的数据库网址。改变这个

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")) {
相关问题