2010-11-13 52 views
2

我似乎無法獲得我的Java程序與java的連接,我啓動了MySQL服務器,在phpMyAdmin中創建了一個數據庫。但是我對如何使用從MySQL下載的JDBC驅動程序感到困惑。如何在JAVA中創建一個MySQL連接

這裏是我的代碼:

private void startConnection() 
{ 
Connection conn = null; 
String url = "jdbc:mysql://localhost/"; 
String dbName = "bank"; 
String driver = "com.mysql.jdbc.Driver"; 
String userName = "root"; 
String password = "password"; 
try { 
    Class.forName(driver).newInstance(); 
    conn = DriverManager.getConnection(url+dbName,userName,password); 
    System.out.println("Connected to the database"); 
    conn.close(); 
    System.out.println("Disconnected from database"); 
} catch (Exception e) { 
    System.out.println("NO CONNECTION =("); 
} 
} 

我已經列入我的JDK的jar文件 - JRE \ LIB \ ext文件夾,但沒有。有任何想法嗎?

在此先感謝。

+3

這是什麼代碼的控制檯輸出? – 2010-11-13 13:22:57

+1

你得到的錯誤是什麼?代碼看起來不錯。爲了得到確切的錯誤,在你的catch子句中使用'e.printStackTrace();'。 – ZeissS 2010-11-13 13:23:45

+0

在您的異常處理程序中,請*打印出堆棧跟蹤或至少e.getMessage()!! – 2010-11-13 13:24:22

回答

3

有一點突出:您沒有在URL中指定網絡端口。默認端口是3306.因此請嘗試:

jdbc:mysql://localhost:3306/ 

對於URL。

+0

進行搜索,嘗試使用端口號,仍然無法使用。我已經在上面的評論中發佈了堆棧跟蹤。 – 2010-11-13 13:30:16

+0

2件事情:首先,檢查您爲MySQL驅動程序提供的jar文件是在類路徑中還是在jre \ lib \ ext文件夾中。其次,查看jar文件(例如'jar tf')並查看是否存在'com/mysql/jdbc/Driver.class'。 – corriganjc 2010-11-13 13:47:12

+0

另外,如果您的Java應用程序在您將MySQL驅動程序jar添加到類路徑中後未重新啓動,則需要重新啓動它。 – corriganjc 2010-11-13 13:52:06

1

您必須指定端口。它默認爲String url = "jdbc:mysql://localhost:3306/";

0
private void startConnection() 
{ 
    Connection conn = null; 
    String url = "jdbc:mysql://localhost:3306/"; 
    String dbName = "bank"; 
    String driver = "com.mysql.jdbc.Driver"; 
    String userName = "root"; 
    String password = "password"; 

    try 
    { 
     Class.forName(driver).newInstance(); 
     conn = DriverManager.getConnection(url+dbName,userName,password); 
     System.out.println("Connected to the database"); 
     conn.close(); 
     System.out.println("Disconnected from database"); 

    } 
    catch (Exception e) 
    { 
     System.out.println("NO CONNECTION =("); 
    } 
} 

這將工作