问题:建立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中没有下载对应的驱动包
解决:
- 首先在MySQL官网下载对于版本的驱动安装包
https://downloads.mysql.com/archives/c-j/
- 选择对应的版本,Operating System 选择Platform Independent
文件后缀名为 .tar.gz 的是Linux/IOS的压缩包;后缀为 .zip 的是Windows下的压缩包,根据系统选择下载。
- 解压,我们需要.jar文件,将安装包复制到项目中的lib文件夹中
- 打开IDEA,File -> Project Structure -> Modules -> Dependencies -> 点击右边绿色的‘+’
- 选第一个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>