解决"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"

时间:2023-03-09 18:31:03
解决"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"

按照以前的老方法,写Java的主程序通过JDBC来连MySQL。

//1: import java.sql.*;
import java.sql.*; public class JDBC_Driver {
// JDBC driver name and database URL;
static final String dbDriver = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/mysql"; // database credentials
static final String USER = "your username";
static final String PWD = ""; // input your passoword public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
//2. Register JDBC driver (not necessary any more)
Class.forName("com.mysql.jdbc.Driver"); //3. open a connection
System.out.println("Connecting to database");
conn = DriverManager.getConnection(DB_URL, USER, PWD); //4. create statement
System.out.println("Creating statement");
stmt = conn.createStatement(); //5. execute query;
String sql;
sql = "select * from items";
rs = stmt.executeQuery(sql); //6. extract data from result set
while(rs.next()){
//retrieve by column name
int id = rs.getInt(1);
String name = rs.getString(2);
double price = rs.getDouble(3); // display values
System.out.print("ID: " + id + " ");
System.out.print("name: " + name + " ");
System.out.print("price: " + price + " ");
System.out.println(); }
rs.close();
stmt.close();
conn.close();
}
catch (Exception e) {
System.out.println("Error: " + e);
} } }

解决"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"

报错了!老说是在"forClass"那儿错了。

解决办法是要引入JDBC的driver。上次做的project是用的Oracle,这次自己却粗心了。

所以按照“Java Web整合开发实战”P44的方法,在Eclipse里面用JDBC连接MySQL的数据库。下载了"connector/j"的jar文件,然后在项目里新建文件夹lib,把MySQL的JDBC driver拖拽进来。

解决"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"

随后又在整个项目的Java Build Path里面把driver作为作为internal jar导入。

解决"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"

另外一种方法,新建lib文件夹,直接在"Java Build Path"里面添加一个External Jar也可以达到同样的效果。

参考的视频: https://www.youtube.com/watch?v=oBeB2YqOCpU