我知道关于这个主题有很多问题,但我觉得我面临的情况确实不同。
问题:
我创建了一个 RCP 项目,在其中我需要连接到我的 Mysql 数据库。在编写程序之前,我编写了一个测试程序来测试所需的配置,并且成功连接到 Mysql 数据库。测试程序见附件1。
然后我开始在同一个项目中编写我的程序,但是当我调用其中的函数时,发生了异常java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
。这真的让我很不安。方案见附件2。
附录1 Sql.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sql
{
private static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
private static final String URL ="jdbc:mysql://localhost/manager?useUnicode=true&characterEncoding=utf8";
private static final String USERNAME = "root";
private static final String PASSWORD = "yhl0821";
public static void main(String[] args)
{
Connection con = null;
Statement sm = null;
ResultSet rs=null;
try
{
Class.forName(MYSQL_DRIVER);
con =DriverManager.getConnection(URL, USERNAME, PASSWORD);
System.out.println("Successed to connect the mysql!");
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
附录2 EventEntity.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class EventEntity
{
private static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost/manager?useUnicode=true&characterEncoding=utf8";
private static final String USERNAME = "root";
private static final String PASSWORD = "yhl0821";
public static List<Object> getEventEntity()
{
List<Object> list = null;//
Connection con = null;
Statement sm = null;
ResultSet rs = null;
try
{
Class.forName(MYSQL_DRIVER); //this is the setence creating exception
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
System.out.println("Successed to connect the mysql!");
sm = con.createStatement();
rs = sm.executeQuery("select * from systemevent ");//
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
return list;
}
}
最佳答案
当您运行附录 2 中的程序时,类 com.mysql.jdbc.Driver
不在您的 CLASSPATH 中。
关于java.lang.ClassNotFoundException : com. mysql.jdbc.Driver。一个项目中有两个程序,一个可以运行,另一个不能运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824464/