Java 運行時錯誤:ClassNotFoundException:com.mysql.jdbc.Driver
問題描述:
問題描述:問題描述:
可能的原因:
缺少JDBC 驅動程式庫:應用程式的運行時類路徑中缺少com.mysql. jdbc.Driver 類別。
<code class="java">// import packages import java.sql.*; // create class ClientBase public class ClientBase { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/CLIENTBASE"; // Database credentials static final String USER = "root"; static final String PASS = ""; // Begin method main public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // Register JDBC driver Class.forName(JDBC_DRIVER); // Add this line if the driver is not found // Open connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); // Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, name, address, address 2, city, phone, state, zip, fax FROM CLIENTBASE"; ResultSet rs = stmt.executeQuery(sql); // Extract data from result set while (rs.next()) { // Retrieve by column name int id = rs.getInt("id"); String name = rs.getString("name"); String address = rs.getString("address"); String address2 = rs.getString("address2"); String city = rs.getString("city"); String phone = rs.getString("phone"); String state = rs.getString("state"); String zip = rs.getString("zip"); String fax = rs.getString("fax"); // Display values System.out.print("ID: " + id); System.out.print(" Name: " + name); System.out.println("Address:" + address); System.out.println(address2); System.out.print("City:" + city); System.out.print(" State: " + state); System.out.println(" Zip: " + zip); System.out.print("Phone: " + phone); System.out.println(" Fax: " + fax); } // end while // clean up rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // finally block used to close resources try { if (stmt != null) stmt.close(); } catch (SQLException se) { se.printStackTrace(); } // end finally } // end try System.out.println("Goodbye."); } // End method main } // end class ClientBase</code>Linux/Mac: java -cp .:mysql-connector-java-5.1.25-bin.jar ClientBase範例程式碼:範例程式碼:
以上是使用 JDBC 連接到 MySQL 資料庫時,為什麼會收到「ClassNotFoundException: com.mysql.jdbc.Driver」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!