当前位置:   article > 正文

数据库连接失败_“encrypt”属性设置为“true”且 “trustservercertificate”属性设置

“encrypt”属性设置为“true”且 “trustservercertificate”属性设置为“false

狂神说第一个jdbc程序


正确代码

mysql版本:5.7.19
数据驱动包:mysql-connector-java-5.1.47-bin.jar(要放到 lib文件下)

import java.sql.*;
/**
 * @Classname jdbctest1
 * @Description TODO
 * @Date 2022/1/4 12:07
 * @Created by cencen
 */
public class jdbctest1 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载数据
        Class.forName("com.mysql.jdbc.Driver");//固定写法,加载驱动

        //2.用户信息和url
        //useUnicode=true&characterEncoding=utf8&useSSL=true
        String url = "jdbc:mysql://localhost:3306/jdbcstudy?characterEncoding=UTF8&useSSL=false";
        String username = "root";
        String password = "20020809l";

        //3.连接成功,数据库对象 Connection代表数据库
        Connection connection = DriverManager.getConnection(url,username,password);

        //4.执行sql的对象 Satement 执行sql的对象
        Statement statement = connection.createStatement();

        //5.执行sql的对象去执行sql,可能存在结果,查看返回结果
        String sql = "SELECT * FROM users";

        ResultSet resultSet = statement.executeQuery(sql);//返回的结果集,结果集中封装了我们全部的查询出来的结果

        while(resultSet.next()){
            System.out.println("id=" + resultSet.getObject("id"));
            System.out.println("id=" + resultSet.getObject("name"));
            System.out.println("id=" + resultSet.getObject("password"));
            System.out.println("id=" + resultSet.getObject("email"));
            System.out.println("id=" + resultSet.getObject("birthday"));
            System.out.println("--------------------------------------------");
        }

        //6.释放连接
        resultSet.close();
        statement.close();
        connection.close();

    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

成功前的报错

1.mysql端口被占用(我的错误)

请添加图片描述
因为端口被占用,导致账户和密码不能组合,因此无法连接

解决办法:
1.打开服务关掉除了mysql之外的关于sql service的服务
请添加图片描述
2.在idea中
在这里插入图片描述
点开mysql
在这里插入图片描述
导入jar包
在这里插入图片描述
选择你事先下载好的jar包,
否则会报下载驱动错误:Driver class ‘com.mysql.cj.jdbc.Driver’ not found.

在这里插入图片描述

填入相应信息,点击下方Test Connection 有绿勾即可
在这里插入图片描述


本次问题关键
输入密码总是提示错误
请添加图片描述
原因就是mysql端口被占用,导致无法连上数据库,密码和用户名无法匹配


2.useSSL设为false(其实true也行)

建议不要在没有服务器身份验证的情况下建立SSL连接。根据MySQL 5.5.45 +,5.6.26 +和5.7.6+要求如果未设置显示选项,则必须默认建立SSL连接。为了符合不使用SSL的现有应用程序,verifyServerCertificate属性设置为“false”。您需要通过设置useSSL = false显式禁用SSL,或者设置useSSL = true并为服务器证书验证提供信任库。

3.时区问题据说在mysql8以上的版本才需要添加

即在url中再加 &serverTimezone=Asia/Shanghai

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/418903
推荐阅读
相关标签
  

闽ICP备14008679号