2016-09-14 153 views
0

我在phpMyAdmin有一個練習數據庫。我使用XAMPP。我正處於與數據庫相關的初級階段。我遵循教程,我認爲我理解這個概念,一切都很酷。但是,我提出了一個問題,儘管互聯網上有答案,但我無法解決這個問題。這裏是我的代碼:到mySQL數據庫的Java連接

import java.sql.*; 

public class DBConnect { 

    private Connection connection; 
    private Statement statement; 
    private ResultSet result; 

    public DBConnect(){ 
     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
      connection = DriverManager.getConnection("jdbc:mysql://localhost:1234/practicedb"); //code stucks here and after some minutes it is throwing an exception 
      System.out.println("Connected");//this is never executed. 
      statement = connection.createStatement(); 

     } catch (Exception ex) { 
      System.out.print("Error in Constractor: "+ex); 
     } 
    } 

    public void getData() { 

     try { 

      String query = "select * from cars"; 

      result = statement.executeQuery(query); 
      while (result.next()) { 
       String name = result.getString("carName"); 
       String id = result.getString("carID"); 
       String modelNum = result.getString("modelNumber"); 
       System.out.println("Car name: " + name + ", " + "Car ID: " + id + ", " + "Car model number: " + modelNum); 
      } 

     } catch (Exception ex) { 
      System.out.println(ex); 
     } 

    } 
} 

在主類我創建類的實例,然後調用getData()

代碼stucks在該行:

connection = DriverManager.getConnection("jdbc:mysql://localhost:1234/practicedb"); 

它拋出:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 

成功發送到服務器的最後一個數據包爲0毫秒前。司機還沒有從server.java.lang.NullPointerException

這類似的問題,在這裏回答任何接收到的數據包:answer

但建議是窮人。我曾嘗試沖洗dns。我檢查了URL,這是我在phpmyadmin上連接到數據庫的那個URL。我將localhost更改爲我的IP地址。但所有那些只是不工作。

我真的很感激幫助。是設法接受這些知識的第一步,而我現在實際上不能繼續進行。謝謝:)

  • 我注意到,如果我將localhost:1234更改爲像localhost:5432這樣的隨機一個,它立即拋出錯誤。但是,當我有它在1234年(我通過xampp配置選擇端口)然後程序運行約五分鐘之前,它終止異常
+5

爲什麼你(嘗試)在端口1234連接? MySQL偵聽3306 – tkausl

+0

驗證數據庫是否已啓動並運行以下命令:netstat -ano | findstr 1234(如果在windows上),如果在linux上netstat -anp | grep 1234.你看到類似這樣的「TCP 0.0.0.0:3389 0.0.0.0:0 LISTENING 1316」(最後一個數字是PID,確認它與mysql服務器相同) –

+0

你的連接字符串中的userName和Password在哪裏? 通常我使用這樣的smth: 'String url =「jdbc:mysql://127.8.92.130:3306 /」; String dbName =「test」; String driver =「com.mysql.jdbc.Driver」; String userName =「admin」; String password =「pass」; String sslState =「?useSSL = false」; con = DriverManager.getConnection(url + dbName + sslState,userName,password);' –

回答

-3

通常MySQL偵聽默認端口3306。 如果你的數據庫名爲practicedb那麼你的代碼應該是這樣的:

private Connection connection;  

try { 
    connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/practicedb"); 
    System.out.println("Connected"); 
} catch (Exception ex) { 
    System.out.print("Error creating connection: "+ex); 
} 
+0

我已將默認端口更改爲1234,因爲默認端口有衝突 –

+0

歡迎使用StackOverflow!我不確定你爲什麼如此嚴厲地被低估。你的回答可能包含更多的解釋,但絕對是我的第一個想法(雖然海報的編輯看起來不是這樣)。 –