IDEA web项目无法连接数据库——java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver

问题:建立web项目,无法连接数据库,一直以为是rs.close();出错。最后将代码块分开,才发现报错是数据库驱动没有加载上。
环境:IDEA
MySQL 8.0.13
appach-tomcat 9.0.332
jdk1.8

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

问题1:MySQL不同版本对应的驱动不同

com.mysql.jdbc.Driver 是 mysql-connector-java 5中的;
com.mysql.cj.jdbc.Driver 是 mysql-connector-java 6中的。

问题2:在IDEA中没有下载对应的驱动包
解决:

  1. 首先在MySQL官网下载对于版本的驱动安装包

https://downloads.mysql.com/archives/c-j/

  1. 选择对应的版本,Operating System 选择Platform Independent
    文件后缀名为 .tar.gz 的是Linux/IOS的压缩包;后缀为 .zip 的是Windows下的压缩包,根据系统选择下载。
    在这里插入图片描述
  2. 解压,我们需要.jar文件,将安装包复制到项目中的lib文件夹中
    在这里插入图片描述
  3. 打开IDEA,File -> Project Structure -> Modules -> Dependencies -> 点击右边绿色的‘+’
  4. 选第一个JARs of directories,找到你刚刚解压的位置,选中文件mysql-connector-java-8.0.13.jar-> 点OK
    在这里插入图片描述
    最后,重新加载一下,或者将IDEA关闭重启。

附上web连接数据库代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.*"%>
<html>
<head>
    <title>mysql连接</title>
</head>
<body>
<%!
    public static final String dbdriver="com.mysql.cj.jdbc.Driver";
    public static final String dburl="jdbc:mysql://127.0.0.1:3306/myidea?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false";
    public static final String dbuser="root";
    public static final String dbpass="sql2008";
%>
<%
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs= null;
%>
<%
    try{
        Class.forName(dbdriver);
        conn = DriverManager.getConnection(dburl,dbuser,dbpass);
        String sql="select * from emp";
        pstmt = conn.prepareStatement(sql);
        rs=pstmt.executeQuery();
        System.out.println(rs.first());

    }catch(Exception e){
        System.out.println(e);
    }finally{
            rs.close();
            pstmt.close();
            conn.close();
    }
%>
</body>
</html>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值