Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 算法 小程序 Arthas JVM juc AQS Docker DevOps


Java JDBC 获取数据库链接

Java 大约 2458 字

方法一

Class<?> clazz = Class.forName("com.mysql.jdbc.Driver");
// Driver driver = (Driver) clazz.newInstance();
Driver driver = (Driver) clazz.getDeclaredConstructor().newInstance();

String url = "jdbc:mysql://localhost:3306/test?useSSL=false";

Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "123456");

Connection connection = driver.connect(url, info);
System.out.println(connection);

方法二

Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
Connection connection = DriverManager.getConnection(url, "root", "123456");
System.out.println(connection);

方法三

配置文件jdbc.properties

user=root
password=123456
url=jdbc:mysql://localhost:3306/test?useSSL=false
driverClass=com.mysql.jdbc.Driver

ResourceBundle读取配置文件

ResourceBundle bundle = ResourceBundle.getBundle("jdbc"); // 只需要写文件名 jdbc,不需要写扩展名 .properties
String user = bundle.getString("user");
String password = bundle.getString("password");
String url = bundle.getString("url");
String driverClass = bundle.getString("driverClass");

Class.forName(driverClass);

Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);

无需注册驱动原因

MySQL类加载时静态代码块中自动注册了驱动。

package com.mysql.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    public Driver() throws SQLException {
    }

    static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }
}

无需 Class.forName 原因

对于MySQL驱动来说,甚至可以省略Class.forName方法的调用,原因是MySQL驱动包下META-INF下的services文件夹下的java.sql.Driver文件中声明了com.mysql.jdbc.Driver驱动。

MySQL

可能的错误

Tue Feb 15 13:53:49 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.

解决方法

添加useSSL=false参数

jdbc:mysql://localhost:3306/test?useSSL=false

驱动下载

https://downloads.mysql.com/archives/c-j

阅读 109 · 发布于 2022-04-10

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批