2013-10-31 114 views
0

我使用account(root,mypassword)在Mac上安裝mysql。我可以通過這個帳戶通過「MySQL查詢瀏覽器」連接到數據庫。但是,當我嘗試通過Java驅動程序連接時,我遇到了一個異常: java.sql.SQLException:訪問被用戶'root'@'localhost'拒絕(使用密碼:YES)SQLException:訪問被拒絕用戶'root'@'localhost'

我知道很多人與我有同樣的問題。我閱讀並嘗試了很多關於https://stackoverflow.com/的相關主題。但它不能解決我的問題。 你能幫我嗎?

謝謝您的高級。

這裏是我的代碼

System.out.println("-------- MySQL JDBC Connection Testing ------------"); 

try { 
    Class.forName("com.mysql.jdbc.Driver"); 
} catch (ClassNotFoundException e) { 
    System.out.println("Where is your MySQL JDBC Driver?"); 
    e.printStackTrace(); 
    return; 
} 

System.out.println("MySQL JDBC Driver Registered!"); 
Connection connection = null; 

try { 
    connection = (Connection) DriverManager 
    .getConnection("jdbc:mysql://localhost:3306/test","root", "mypassword"); 

} catch (SQLException e) { 
    System.out.println("Connection Failed! Check output console"); 
    e.printStackTrace(); 
    return; 
} 

if (connection != null) { 
    System.out.println("You made it, take control your database now!"); 
} else { 
    System.out.println("Failed to make connection!"); 
} 
+0

請列出您嘗試過的一些方法(例如http://stackoverflow.com/questions/17908273/access-denied-for-user-rootlocalhost?rq=1)以及您的結果。要麼你有一個共同的問題比其他答案將幫助。或者你有一個不尋常的比其他方法的結果將有助於解決。 –

+0

謝謝。我試過了:從控制檯連接到mysql,然後運行本文提到的命令,但它不起作用。 –

+1

請編輯你的問題的結果。列出'mysql.user'表的內容。並且請開始考慮其他可能相關的信息並提供它們。如果你仔細閱讀其他問題(和答案!),你會注意到經常被問到的問題,所以請在你的問題中,澄清爲什麼這不是你的情況(不要只說'它不是這樣',證明它通過增加相關細節)。對於想要幫助你的人來說,每花費好幾分鐘就可以問好問題。 –

回答

0
create user 'myUser'@'*' identified by 'mypassword'; 
grant all privileges on test.* to 'myUser'@'%' identified by 'mypassword' with grant option; 
flush privileges; 

在你的MySQL實例,請嘗試以下三條線。然後在您的Java代碼中,將登錄名從根改爲myUser。

+0

謝謝。但它不起作用。你可以在你的機器上重試嗎? –

相關問題