2013-04-04 25 views
0

我一直有問題指定的路徑(我有兩個文件:comments.frm和db.opt在以下文件夾中:C:\ xampp \ mysql \ data \ feedback)...我使用XAMPP和mySQL。我不知道爲什麼我有錯誤?請看看我的這部分代碼:如何使用localhost指定mySQL的路徑?

public void readDataBase() throws Exception { 
    try { 
     // This will load the MySQL driver, each DB has its own driver 
     Class.forName("com.mysql.jdbc.Driver"); 
     // Setup the connection with the DB 
    connect = DriverManager 
     .getConnection("jdbc:mysql://localhost//feedback" 
       + "user=root&password=1234"); 

PS:我的本地主機密碼爲12345678

+3

你有什麼錯誤? – 2013-04-04 08:03:49

+0

由於您將'user'連接到'feedback',因此連接字符串將會出錯:'jdbc:mysql:// localhost // feedbackuser = root&password = 1234'。 – maba 2013-04-04 08:06:57

回答

2

你應該嘗試

DriverManager.getConnection("jdbc:mysql://localhost/feedback", "root", "1234"); 
2

嘗試

connect = DriverManager 
    .getConnection("jdbc:mysql://localhost/feedback?user=root&password=1234") 

(你在「反饋」後忘了問號)

2

爲了更清晰起見,您可以在獲取連接時使用其他重載方法。

Class.forName("com.mysql.jdbc.Driver"); 
conn = DriverManager.getConnection("jdbc:mysql://<db_ip>/<db_name>", 
    "<username>", "<pwd>"); 
1

我認爲你需要使用:

DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback", "root", "1234"); 

我檢查我的老項目,發現我不使用這裏/feedback雙斜線。

,你也可以像這樣指定編碼:

DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback?characterEncoding=UTF-8&characterEncoding=Cp1251", "root", "1234"); 

,也多了一個建議。不要使用硬編碼。從屬性文件中獲取網址,密碼和用戶名。

1

試試這個希望它能幫助你!

Class.forName("com.mysql.jdbc.Driver"); 
connect = DriverManager.getConnection("jdbc:mysql://localhost/feedback?"+"user=root&password=1234"); 

也看到了網址誤區,如:

jdbc:mysql://localhost//feedback? 

// after localhost... check and try my code... 

1

許多答案,但每個人都忘記了數據庫的端口。

如果你使用mysql,那麼嘗試3306作爲db端口。
http://www.petefreitag.com/articles/jdbc_urls/ - JDBC的網址(例子)的列表

try 
{ 
    conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName, user, passwd); 
} 
catch(SQLException sqle) 
{ 
    System.out.println("Connection fails: " + sqle.getMessage()); 
}