2016-04-26 34 views
0

我與BlueJ的一個新的程序員,我不得不創建一個名爲Connexion類連接到我的MySQL數據庫,但我得到這個錯誤:如何解決「拋出java.lang.ClassNotFoundException:com.mysql.jdbc.Driver」與BlueJ的和Wampserver

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

我的代碼:

import java.sql.* ; 

public class Connexion{ 

    /** 
    * Connect to MySQL and read the table "Etat", then 
    * print the contents of the first column. 
    */ 
    public static void test() 
    { 
     try 
     { 
       // Load the database driver 
       Class.forName("com.mysql.jdbc.Driver") ; 

       // Get a connection to the database 
       Connection conn = DriverManager.getConnection( 

       "jdbc:mysql://localhost:3306/OACA?user=root&password=") ; 

       // Print all warnings 
       for(SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning()) 
       { 
        System.out.println("SQL Warning:") ; 
        System.out.println("State : " + warn.getSQLState() ) ; 
        System.out.println("Message: " + warn.getMessage() ) ; 
        System.out.println("Error : " + warn.getErrorCode()) ; 
       } 

       // Get a statement from the connection 
       Statement stmt = conn.createStatement() ; 

       // Execute the query 
       ResultSet rs = stmt.executeQuery("SELECT * FROM Etat") ; 

       // Loop through the result set 
       while(rs.next()) 
       System.out.println(rs.getString(1)) ; 

       // Close the result set, statement and the connection 
       rs.close() ; 
       stmt.close() ; 
       conn.close() ; 
     } 
     catch(SQLException se) 
     { 
       System.out.println("SQL Exception:") ; 

       // Loop through the SQL Exceptions 
       while(se != null) 
       { 
        System.out.println("State : " + se.getSQLState() ) ; 
        System.out.println("Message: " + se.getMessage() ) ; 
        System.out.println("Error : " + se.getErrorCode()) ; 

        se = se.getNextException() ; 
       } 
     } 
     catch(Exception e) 
     { 
       System.out.println(e) ; 
     } 
    } 
     public static void main(String[] args) { 
     test(); 
    } 
} 

那麼,如何連接到我的Wampserver中的MySQL v5.6.17數據庫。 我認爲我需要一個coonector.jar但我不知道我會真正需要哪一個。 你能給出你的意見嗎?

+0

可能重複:http://stackoverflow.com/questions/17484764/java-lang-classnotfoundexception-com-mysql-jdbc-driver-in-eclipse –

回答

0

您可能需要將驅動程序包含在類路徑中。 如果你使用Maven,添加驅動程序作爲依賴在你的pom.xml文件

是這樣的:

<dependency> 
    <groupId>mysql</groupId> 
    <artifactId>mysql-connector-java</artifactId> 
    <version>5.1.38</version> 
</dependency> 

如果你不使用Maven,試圖在這一問題提出的解決方案:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

+0

我固定它是與連接器問題但在我的代碼中System.out.println(rs.getString(1)); System.out.println(rs.getString(2)); System.out.println(rs.getString(3)); System.out.println(rs.getString(4)); System.out.println(rs.getString(5));當我運行它時,它並沒有給我所有的內容 – MakBad

相關問題