doc: update docs/java.md (#909)

This commit is contained in:
witt 2024-12-23 22:09:55 +08:00 committed by GitHub
parent 933b1957e4
commit 44e775a1ee
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1558,6 +1558,118 @@ int frequency = Collections
.frequency(list, 2); // frequency = 2
```
操纵数据库
----
### JDBC
```java
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "123456";
String sql = "SELECT 1 as a, '2' as b";
String preparedSql = "SELECT * FROM t_user WHERE id = ?";
Connection conn = null;
Statement sm = null;
ResultSet rs = null;
try {
// 1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
// 驱动找不到
throw new RuntimeException(e);
}
// 2.建立连接
try (Connection connection = DriverManager.getConnection(url, user, password)) {
conn = connection;
// 3.创建Statement对象
try (Statement statement = connection.createStatement()) {
sm = statement;
// 4.执行SQL语句
try (ResultSet resultSet = statement.executeQuery(sql)) {
rs = resultSet;
// 5.处理结果集
while (resultSet.next()) {
// 按照列名取值
System.out.println(resultSet.getLong("a"));
// 按照索引取值
System.out.println(resultSet.getString(2));
}
}
}
// 3.创建PreparedStatement对象
try (PreparedStatement preparedStatement = connection.prepareStatement(preparedSql)) {
sm = preparedStatement;
preparedStatement.setLong(1, 1_000L);
// 4.执行SQL语句
try (ResultSet resultSet = preparedStatement.executeQuery()) {
rs = resultSet;
// 5.处理结果集
while (resultSet.next()) {
System.out.println(resultSet.getLong("id"));
System.out.println(resultSet.getString(2));
}
}
}
} catch (SQLException e) {
// 数据库异常
throw new RuntimeException(e);
} finally {
// 6.关闭资源
// 上面的try块里已经自动关闭否则JDK 7以前按照以下顺序关闭
// 先打开的后关闭,后打开的先关闭
if (null != rs) {
try {
rs.close();
} catch (SQLException ignored) {
}
}
if (null != sm) {
try {
sm.close();
} catch (SQLException ignored) {
}
}
if (null != conn) {
try {
conn.close();
} catch (SQLException ignored) {
}
}
// 也可以直接工具类, 注意顺序
IOUtils.close(rs);
IOUtils.close(sm);
IOUtils.close(conn);
}
```
### JDBC注册驱动
```java
Class.forName("com.mysql.cj.jdbc.Driver");
DriverManager.registerDriver(new org.postgresql.Driver());
// 支持多个同时注册
System.setProperty("jdbc.drivers", "com.mysql.cj.jdbc.Driver:org.postgresql.Driver");
```
另见
---