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
驱动下载
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

-
PHP 获取毫秒值时间戳阅读 2309
-
软考-系统架构设计师:NoSQL阅读 1385
-
PowerShell 快捷键阅读 606
-
PowerShell 使用 wget 只输出信息不下载问题阅读 2368
-
HTML input 输入框禁止显示输入过的历史数据阅读 730
-
Kubernetes Ingress 控制器 Nginx阅读 184
-
IDEA 滚轮调节字体大小阅读 1598
-
Nginx 配置之开启状态检查阅读 1499
-
软考-系统架构设计师:物联网 IoT阅读 905
-
MySQL Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root阅读 1755