2013-10-20 63 views
1

我試圖通過localhost從JDBC連接到MySQL。但連接失敗。在例外,我看到JDBC試圖連接到127.0.0.1JDBC MySQL自動將localhost轉換爲127.0.0.1

String connectionString = ""; 
    try { 
     loadProperties(); 
     Class.forName("com.mysql.jdbc.Driver"); 
     // Setup the connection with the DB 
     connectionString = "jdbc:mysql://" + properties.getProperty("host") + "/" + properties.getProperty 
       ("database") + "?user=" + properties.getProperty("user") + "&password=" + properties 
       .getProperty 
         ("password"); 
     connect = DriverManager 
       .getConnection(connectionString); 
     logger.debug("Connected to " + properties.getProperty("host")); 
    } catch (Exception e) { 
     logger.error("Database Connection failed with connection string - " + connectionString,e); 
    } 

從日誌:

Database Connection failed with connection string - jdbc:mysql://localhost/testdb?user=testuser&password=testpass 

java.sql.SQLException: Access denied for user 'testuser'@'127.0.0.1' (using password: YES) 

爲什麼用127.0.0.1替換本地主機?我只爲本地主機配置了登錄。

回答

1

IP地址127.0.0.1是保留用於每臺計算機的專用地址。傳統上,127.0.0.1是計算機的環回地址。 網絡軟件和實用程序可以使用127.0.0.1訪問本地計算機的TCP/IP網絡資源。發送到回送IP地址(如127.0.0.1)的消息不會到達局域網(LAN)外部,而是由計算機自己的網絡適配器自動重新路由回到TCP/IP堆棧的接收端。簡而言之,localhost也可以被稱爲127.0.0.1。 MySql訪問權限存在問題。這link將幫助您解決它

+0

我知道這一點。但是我的MySQL服務器只對本地主機開放,而不是對任何其他IP地址,包括127.0.0.1 – emaillenin

+0

你有你的hosts文件配置映射嗎? – Keerthivasan

+0

是的。我有'127.0.0。1 \t localhost' in my'/ etc/hosts' – emaillenin

4

當遇到同樣的問題時,我偶然發現了這個問題。

要回答這個問題:「爲什麼用127.0.0.1替換本地主機?」:

MySQL docs,在您的連接URL使用localhost意味着你要連接到一個插座。使用127.0.0.1意味着你想通過TCP/IP連接。

在Unix上,MySQL程序專門處理主機名localhost,其方式可能與您期望的與其他基於網絡的程序相比有所不同。對於連接到本地主機,MySQL程序試圖通過使用Unix套接字文件連接到本地服務器。 ......爲了確保客戶端建立TCP/IP連接到本地服務器,用--host或-h指定127.0.0.1

根據this answer的主機名值,看來通過默認的JDBC僅支持TCP/IP連接,至少對於某些Java版本。原始來源:http://lists.mysql.com/java/8749

Java本身不支持UNIX域套接字

所以,我猜想,因爲只有JDBC連接通過TCP/IP,將其轉換localhost127.0.0.1內部。

爲了解決這個問題,在我的情況: