Java 运行时错误:ClassNotFoundException:com.mysql.jdbc.Driver
问题描述:
使用 JDBC 连接到 MySQL 数据库的 Java 应用程序在尝试实例化 MySQL JDBC 驱动程序时遇到“ClassNotFoundException”。
可能的原因:
解决方案:
将 JDBC 驱动程序添加到类路径: 将 MySQL JDBC 驱动程序 JAR 文件(例如 mysql-connector-java-5.1.25-bin.jar)添加到应用程序的类路径。这可以在使用“-cp”参数运行应用程序时完成:
示例代码:
<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>
以上是使用 JDBC 连接到 MySQL 数据库时,为什么会收到“ClassNotFoundException: com.mysql.jdbc.Driver”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!