Java JDBC 获取数据库链接
Java 评论 1 大约 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扫描下方二维码关注公众号和小程序↓↓↓

-
fHLvlxbf 1楼
e
Chrome | Windows 10 2023-07-24
-
Android ListView 条目上有 CheckBox 抢焦点的处理办法阅读 2136
-
Spring 事务失效的几种场景阅读 1337
-
Git OpenSSL errno 10054阅读 1070
-
SpringMVC 使用对象接收 GET 请求参数 QueryString阅读 780
-
MySQL 中文全文检索 ngram 处理停止词阅读 4240
-
Kubernetes 本地访问 Service 中的资源阅读 362
-
走进 Spring Boot 第二步之 SpringApplicaiton 构造函数阅读 3951
-
Linux 不排序去除重复行和不排序统计重复行阅读 5685
-
PHP 获取毫秒值时间戳阅读 3361
-
Spring Boot @Scheduled 定时任务阅读 4762