MySQL 8.0 以上版本的数据库连接有所不同:
1、MySQL 8.0 以上版本驱动包版本 mysql-connector-java-8.0.16.jar。
2、com.mysql.jdbc.Driver 更换为 com.mysql.cj.jdbc.Driver。
3、MySQL 8.0 以上版本不需要建立 SSL 连接的,需要显示关闭。
4、allowPublicKeyRetrieval=true 允许客户端从服务器获取公钥。
5、最后还需要设置 CST。
import java.sql.*;
public class mySqlDemo {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/cns?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
static final String USER = "root";
static final String PASS = "wei123";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql = "select id, orgName, licNo from cns_data_list limit 10";
ResultSet res = stmt.executeQuery(sql);
// 展开结果集数据库
while(res.next()) {
// 通过字段检索
int id = res.getInt("id");
String orgName = res.getString("orgName");
String licNo = res.getString("licNo");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 站点名称: " + orgName);
System.out.print(", 站点 URL: " + licNo);
System.out.print("\n");
}
// 完成后关闭
res.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
finally {
// 关闭资源
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
System.out.println("GoodBye");
}
}