2017-04-25 31 views
0

我的JDBC代碼根本沒有做任何事情。它會打印出「連接到數據庫」的聲明,但就是這樣。我引用了JDBC jar文件,所以我有點困惑,爲什麼我的代碼不工作。我一直在努力工作的代碼如下。JDBC不起作用

package exampleDatabase; 


import java.sql.*; 


public class Main { 

     // TODO Auto-generated method stub 


     static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
      static final String DB_URL = "jdbc:mysql://localhost:81/companylist"; 

      // Database credentials 
      static final String USER = "root"; 
      static final String PASS = ""; 

      public static void main(String[] args) { 
      Connection conn = null; 
      Statement stmt = null; 

      try{ 
       //STEP 2: Register JDBC driver 
       Class.forName("com.mysql.jdbc.Driver"); 

       //STEP 3: Open a connection 
       System.out.println("Connecting to database..."); 
       conn = DriverManager.getConnection(DB_URL,USER,PASS); 

       //STEP 4: Execute a query 
       System.out.println("Creating statement..."); 
       stmt = conn.createStatement(); 
       String sql; 
       sql = "SELECT ID, firstName, lastName,Email FROM Staff"; 
       ResultSet rs = stmt.executeQuery(sql); 

       //STEP 5: Extract data from result set 
       while(rs.next()){ 
       //Retrieve by column name 
       int ID = rs.getInt("ID"); 
       String firstName = rs.getString("firstName"); 
       String lastName = rs.getString("lastName"); 
       String Email = rs.getString("Email"); 

       //Display values 
       System.out.print("ID: " + ID); 
       System.out.print(", First: " + firstName); 
       System.out.println(", Last: " + lastName); 
       System.out.println(", Last: " + Email); 

       } 
       //STEP 6: Clean-up environment 
       rs.close(); 
       stmt.close(); 
       conn.close(); 
      }catch(SQLException se){ 
       //Handle errors for JDBC 
       se.printStackTrace(); 
      } catch (ClassNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
      } 
    } 
+0

你確定端口81是正確的端口? https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html – maximilianus

+0

您是否收到錯誤訊息?並且數據庫端口地址是否正確?你確定它是'81'嗎? –

+0

嗨,我認爲這是一個端口問題。請檢查這個帖子,看看它是否能解決你的問題。 http://stackoverflow.com/a/26788332/4022947 謝謝 –

回答

0

數據庫服務器的Port Address不是網絡服務器的端口。因此,要解決這個問題,您應該將連接URL更改爲jdbc:mysql://localhost:3306/companylist,因爲3306是MySQL數據庫服務器的默認端口地址。

-1

jdbc:mysql://localhost:81/companylist無效。

由於您使用的是mysql database,因此默認的port服務器數量爲3306

那麼試試這個,jdbc:mysql://localhost:3306/companylist

它將運行....