记录易忘知识点
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
@SpringBootTest
class SpringBootJdbcApplicationTests {
//数据源组件
@Autowired
DataSource dataSource;
//用于访问数据库的组件
@Autowired
JdbcTemplate jdbcTemplate;
@Test
void contextLoads() throws SQLException {
System.out.println("默认数据源为:" + dataSource.getClass());
System.out.println("数据库连接实例:" + dataSource.getConnection());
//访问数据库
Integer i = jdbcTemplate.queryForObject("SELECT count(*) from `tb_user`", Integer.class);
System.out.println("user 表中共有" + i + "条数据。");
String s= jdbcTemplate.queryForObject("SELECT name from `tb_user` where id = 1", String.class);
System.out.println("user 表中数据为" + s );
//实现Maplist多数据查询 易忘♥
System.out.println("默认数据源为:" + dataSource.getClass());
System.out.println("数据库连接实例:" + dataSource.getConnection());
//访问数据库
List<Map<String, Object>> userList = jdbcTemplate.queryForList("SELECT * FROM tb_user");
for (Map<String, Object> user : userList) {
System.out.println(user);
}
}
}