Java改为jdk1.8使用JDBC连接mysql数据库报错问题
报错:
可能是没有导入mysql.connection.jar包或版本不对,要导入Java对应版本的jar,jdk1.8.0可以用下列版本
Mysql-connector-java各版本下载地址:
https://mvnrepository.com/artifact/mysql/mysql-connector-java
解决:
我是直接导入文件夹下:C:\Program Files\Java\jdk1.8.0_251\jre\lib\ext,这不需要在项目中导入额外jar包
之后运行会报错:
解决:
String url = “jdbc:mysql://localhost:3306/database”; 应改为:
String url = “jdbc:mysql://localhost:3306/database?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true”; //连接数据库database, jdk1.8+mysql_connection.jar包后
简述为:
1.引用外部库 mysql-connector-java-8.0.版本的jar
2.jdbc驱动类:com.mysql.jdbc.Driver 改成 com.mysql.cj.jdbc.Driver
3.jdbcUrl:jdbc:mysql://{ip}:{port}/{db}?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
附eclipse测试案例:
以下未将jdbc驱动类:com.mysql.jdbc.Driver 改成 com.mysql.cj.jdbc.Driver,也成功了
package myservlet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCTest {
public static Connection getConnection() {
//url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
String driver = "com.mysql.jdbc.Driver"; // 获取mysql数据库的驱动类
//String url = "jdbc:mysql://localhost:3306/xsxk"; // 连接数据库xsxk, jdk1.7+mysql_connection.jar包
String url = "jdbc:mysql://localhost:3306/xsxk?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true"; //连接数据库xsxk, jdk1.8+mysql_connection.jar包
String name = "root";// 连接mysql的用户名
String pwd = "123456";// 连接mysql的密码
try {
Class.forName(driver); // 1. 加载驱动程序
Connection conn = DriverManager.getConnection(url, name, pwd);// 2.打开数据库连接
return conn;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
Connection cc = JDBCTest.getConnection();
if (!cc.isClosed())
System.out.println("Succeeded connecting to the Database!");
Statement statement = cc.createStatement(); // 3. 获取statement对象
//查询数据
String sql = "select * from student";
ResultSet rs = statement.executeQuery(sql); // 4. 执行SQL语句
while (rs.next()) { // 5. 处理结果集
System.out.println(rs.getString("Sno"));
System.out.println(rs.getString("Sname"));
System.out.println(rs.getString("Ssex"));
}
}
}
先要建立数据库
测试结果: