1. 程式人生 > >Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.driver at java.base/jdk

Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.driver at java.base/jdk

Eclipse下javal連資料庫一直報這個錯。由於我用的是新版的MySQL,所以經常遇見些奇奇怪怪的錯……

坑在這裡: 

錯誤程式碼:Class.forName("com.mysql.jdbc.driver");

Driver要大寫!!!

正確的程式碼:

package testjdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {

	public static void main(String args[]) throws ClassNotFoundException
   {
	//連線mysql資料庫,連線其他的資料庫需要改變格式
	String url = "jdbc:mysql://localhost:3306/mycompany";
    String user ="";//替換成你自已的資料庫使用者名稱
    String password = "";//這裡替換成你自已的資料庫使用者密碼
    String sqlStr = "select ID,Name,Department from person";
    String sqlInsert = "insert into person " +"VALUES (88, 'May', 'R&D')";
    String sqlUpdate = "update person " +"set Department = 'Marketing' where ID in (1,3)";


    try{   //異常處理語句是必需的.否則不能通過編譯!   
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println( "載入驅動成功!" );

        Connection con = DriverManager.getConnection(url, user, password);

        System.out.println( "連線資料庫成功!" );

        Statement st = con.createStatement();
        System.out.println( "建立Statement成功!" );
        
        //新增資料
        st.executeUpdate(sqlInsert);
        System.out.println("新增新資料成功");
        
        //更新資料
        st.executeUpdate(sqlUpdate);
        System.out.println("更新資料成功");

        //查詢資料
        ResultSet rs = st.executeQuery( sqlStr );
        System.out.println( "查詢資料操作成功!" );
        System.out.println( "----------------!" );

        while(rs.next())
        {
          System.out.print(rs.getString("ID") + "   ");
          System.out.print(rs.getString("Name") + "   ");
          System.out.println(rs.getString("Department"));
        }
  
        rs.close();
        st.close();
        con.close();
    }
    catch(SQLException e){
    		System.out.println("ErrorCode:"+e.getErrorCode());
    		System.out.println("SQLState:"+e.getSQLState());
    		System.out.println("reason:"+e.getMessage());    
    }
  }
}

這樣執行後還會有一個錯:

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

因此,需要將com.mysql.jdbc.Driver(已被棄用)改成com.mysql.cj.jdbc.Driver