2016-03-12 45 views
0

錯誤是「異常:無效的數據庫地址:jdbc:mysql:// localhost:3306/library?user = root & password = myPassword」 我正在使用MySQL數據庫並且是初學者,所以我有點困惑。我在MySQL中的數據庫的名稱是「庫」....所以任何人都可以指向正確的方向嗎?爲什麼它不連接到我的數據庫? Java JBDC,

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

} 
} 
} 
+0

您需要註冊您的數據庫驅動程序。類似於'Class.forName(「com.mysql.jdbc.Driver」);' – user1875195

+2

@ user1875195自2007年以來。 – EJP

回答

2

這不是一個有效的數據庫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")) { 
相關問題