使用 JDBC
PPG007 ... 2021-12-26 Less than 1 minute
# 使用 JDBC
# 基本配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306?serverTimezone=UTC
username: root
password: 123456
1
2
3
4
5
6
2
3
4
5
6
# 使用原生 JDBC
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from springmvc.user");
while (resultSet.next()){
System.out.println("id==>"+resultSet.getObject("id"));
System.out.println("name==>" + resultSet.getObject("name"));
System.out.println("sex==>" + resultSet.getObject("sex"));
}
resultSet.close();
statement.close();
connection.close();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
注意
此 DataSource 是javax.sql.DataSource
。
# 使用 JdbcTemplate
@Autowired
JdbcTemplate jdbcTemplate;
@Test
void contextLoads() throws SQLException {
String sql="select * from springmvc.user";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
maps.forEach(System.out::println);
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9