java classnotfoundexception驱动程序未加载

bvn4nwqk  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(394)

这个问题在这里已经有答案了

将java连接到mysql数据库(14个答案)
上个月关门了。
我正在尝试连接到数据库。我试过很多驱动程序,但每次都会抛出一个例外。我不做任何项目。下面是使用javac通过命令行编译的代码。
这是密码

// File JdbcEx.java
//step 1: import package
import java.sql.*;

public class JdbcEx {

public static void main(String args[]) {
    try {
 //Step 2: load driver
        Class.forName("com.mysql.jdbc.Driver");
//Step 3: define the connection URL
        String url = "jdbc:odbc:personDSN";
//Step 4: establish the connection
        Connection con = DriverManager.getConnection(url);
//Step 5: create Statement
        Statement st = con.createStatement();
//Step 6: preapare & execute the query
        String sql = "SELECT * FROM Person";
        ResultSet rs = st.executeQuery(sql);
   //Step 7: process the results
        while (rs.next()) {
 // The row name is "name" in database "PersonInfo,
 // hence specified in the getString() method.
            String name = rs.getString("name");
            String add = rs.getString("address");
            String pNum = rs.getString("phoneNum");
            System.out.println(name + " " + add + " " + pNum);
        }
   //Step 8: close the connection
         con.close();
    } catch (Exception sqlEx) {
        System.out.println(sqlEx);
    }
} // end main
} // end class

每次运行时都会显示以下异常。

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

这个驱动程序会随驱动程序而改变。

o4tp2gmn

o4tp2gmn1#

你错过了这个班的jar com.mysql.jdbc.Driver 在类路径中。尝试使用以下工具运行:

java --class-path=.;nameOfYourJarWithTheClassInIt.jar JdbcEx

相关问题