image.png
    环境:
    数据库Mysql5.7
    数据库驱动版本5.1.48
    数据库名itbz
    准备工作:
    新建JavaProject工程
    添加数据库驱动jar包
    获取数据库连接对象
    下载数据库驱动
    https://downloads.mysql.com/archives/c-j/

    1. import java.sql.Connection;
    2. import java.sql.DriverManager;
    3. import java.sql.SQLException;
    4. /**
    5. * 获取数据库连接测试类
    6. */
    7. public class JDBCTest {
    8. public static void main(String[] args) throws ClassNotFoundException, SQLException {
    9. //连接mysql数据库的url
    10. String url = "jdbc:mysql://localhost:3306/test1?useSSL=false";
    11. //连接数据库的用户名
    12. String name = "root";
    13. //连接数据库的密码
    14. String pwd = "000000";
    15. //通过反射实现数据库驱动的加载与注册
    16. Class.forName("com.mysql.jdbc.Driver");
    17. //通过DriverManager对象获取数据库的连接对象
    18. Connection connection =DriverManager.getConnection(url,name,pwd);
    19. System.out.println(connection);
    20. }
    21. }

    在加载com.mysql.jdbc.Driver类信息时,会执行静态块中的代码。在静态块中 ,数据库驱动会实例化自己并通过DriverManager的registerDriver方法,将自己注册DriverManager驱动管理器中。

    备注:
    image.png
    报错:Wed May 18 21:23:36 CST 2022 WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Exception in thread “main” com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
    翻译:警告:不建议在没有服务器身份验证的情况下建立 SSL 连接。根据 MySQL 5.5.45+、5.6.26+ 和 5.7.6+ 的要求,如果未设置显式选项,则默认情况下必须建立 SSL 连接。为了符合不使用 SSL 的现有应用程序,verifyServerCertificate 属性设置为“false”。您需要通过设置 useSSL=false 来显式禁用 SSL,或者设置 useSSL=true 并为服务器证书验证提供信任库。线程“主”com.mysql.jdbc.exceptions.jdbc4.CommunicationsException 中的异常:通信链接失败
    解决办法:在url后面加 ?useSSL=false
    image.png