java - 我正在尝试通过 jdbc 连接 MySQL 数据库,但代码抛出错误 "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"

标签 java mysql exception jdbc

<分区>

我的代码:

public class database_connection {

public static void main(String[] args) throws SQLException {

     Connection conn = null;
      String url = "jdbc:mysql://localhost:3306/";
      String dbName = "mycooldatab";
      String driver = "com.mysql.jdbc.Driver";
      String userName = "root"; 
      String password = "root";  

      try{
          Class.forName(driver).newInstance();// create object of Driver
          conn = DriverManager.getConnection(url+dbName,userName,password);
          // connection will be established

          // *******************Statement******************
          Statement stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("select * from student");

        //  rs.next(); // 1st row
        //  System.out.println(rs.getString("name"));


                }  catch(Exception e){
            e.printStackTrace();
      }finally{
          conn.close();
      }

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


我曾尝试将以下行添加到系统环境变量的类路径中。

“C:\Program Files (x86)\MySQL\Connector J 5.1.20.0\mysql-connector-java-5.1.20-bin.jar”

但还是不行。我遇到了同样的错误,有人可以找出解决方案并提出解决方案吗?

最佳答案

我怀疑您的类路径设置是否正确。

要验证这一点,请在 main() 的开头添加此行:

 System.out.println("CLASSPATH IS=" + System.getProperty("java.class.path"));

并验证 mysql-connector-java-5.1.20-bin.jar 是否正确显示在该行中。

关于java - 我正在尝试通过 jdbc 连接 MySQL 数据库,但代码抛出错误 "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14150182/

相关文章:

java - 媒体投影需要 ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION 类型的前台服务

java - 加载jar库 加载库

c++ - 从 C++ 中的基实例获取派生类的类型名

haskell - 如何使用没有 SomeException 作为参数类型的处理程序

java - Gradle 错误 Could not find com.actionbarsherlock :actionbarsherlock:4. 4.0 with Eclipse exported project in Android Studio

java - Gradle War 插件 - 重命名库

mysql - 了解 SQL 中的自然连接

php - 循环遍历excel中的记录并使用php中excel文件中的值更新mysql数据库中的特定行

mysql - 错误 1215 (HY000),位于第 : Cannot add foreign key constraint 行

c# - 我应该为失败的文件解析抛出什么异常?