建立数据库连接
本文你会学到:
DriverManager.getConnection() 三种重载方式的区别和适用场景
- JDBC URL 的格式规则和常见数据库的 URL 写法
- 为什么以及如何使用 try-with-resources 确保连接自动关闭
怎样建立数据库连接?——三种重载方式
JDBC 提供三种方式通过 DriverManager 获取连接。
方式一:url + user + password(最常用)
| 三参数方式建立连接 |
|---|
| /**
* 使用 DriverManager.getConnection(url, user, password) 三参数方式建立连接
*/
@Test
void testDriverManagerConnect() throws SQLException {
// 通过 DriverManager 获取数据库连接
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
assertNotNull(conn, "连接对象不应为 null");
// 验证连接是否有效(超时时间 2 秒)
assertTrue(conn.isValid(2), "连接应当有效");
System.out.println("连接是否有效: " + conn.isValid(2));
System.out.println("连接类: " + conn.getClass().getName());
conn.close();
}
|
方式二:仅 URL(将认证信息编码在 URL 中)
| 单参数 URL 方式建立连接 |
|---|
| /**
* 使用 DriverManager.getConnection(url) 单参数版本(H2 无密码场景)
*/
@Test
void testConnectionUrlOnly() throws SQLException {
// 单参数版本:将用户名密码信息编码在 URL 中
// H2 支持在 URL 后追加 ;USER=sa;PASSWORD= 的形式
String urlWithAuth = URL + ";USER=sa;PASSWORD=";
Connection conn = DriverManager.getConnection(urlWithAuth);
assertNotNull(conn, "单参数连接不应为 null");
assertTrue(conn.isValid(2), "单参数连接应当有效");
System.out.println("单参数连接成功: " + conn);
conn.close();
}
|
方式三:Properties 对象传参
| 通过 Properties 对象传入认证信息 |
|---|
| /**
* 使用 Properties 对象传入 user/password 建立连接
*/
@Test
void testConnectionProperties() throws SQLException {
// 通过 Properties 对象设置连接参数
Properties props = new Properties();
props.setProperty("user", USER);
props.setProperty("password", PASSWORD);
Connection conn = DriverManager.getConnection(URL, props);
assertNotNull(conn, "Properties 方式连接不应为 null");
assertTrue(conn.isValid(2), "Properties 方式连接应当有效");
System.out.println("Properties 方式连接成功: " + conn);
conn.close();
}
|
连接字符串怎么写?——JDBC URL 格式
JDBC URL 由三部分组成:
| 数据库 |
URL 示例 |
| H2 内存库 |
jdbc:h2:mem:testdb |
| MySQL |
jdbc:mysql://localhost:3306/mydb |
| PostgreSQL |
jdbc:postgresql://localhost:5432/mydb |
| Oracle |
jdbc:oracle:thin:@localhost:1521:orcl |
连接忘记关闭会怎样?——try-with-resources
Connection 实现了 AutoCloseable 接口,使用 try-with-resources 可确保连接在离开作用域后自动关闭,无需手动调用 close()。
| try-with-resources 自动关闭连接 |
|---|
| /**
* 演示 try-with-resources 自动关闭连接
* 确认连接在离开 try 块后自动关闭
*/
@Test
void testTryWithResources() throws SQLException {
Connection outerRef;
// try-with-resources 自动调用 close(),无需手动关闭
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
outerRef = conn;
assertFalse(conn.isClosed(), "try 块内连接应处于打开状态");
System.out.println("try 块内连接已关闭: " + conn.isClosed());
}
// 离开 try 块后连接自动关闭
assertTrue(outerRef.isClosed(), "离开 try 块后连接应已关闭");
System.out.println("离开 try 块后连接已关闭: " + outerRef.isClosed());
}
|
务必关闭连接
数据库连接属于稀缺资源。未关闭的连接会持续占用数据库服务器端的槽位,最终导致连接耗尽(Too many connections 错误)。
始终使用 try-with-resources 包裹 Connection、Statement、ResultSet。