2020年11月20日:
关于jdbctemplate剩余的查询方式
JdbcTemplate查询-queryForInt返回一个int整数
org.springframework.jdbc.core.JdbcTemplate
类方便执行SQL语句
API介绍
public int queryForInt(String sql)
执行查询语句,返回一个int类型的值。
使用步骤
- 创建JdbcTemplate对象
- 编写查询的SQL语句
- 使用JdbcTemplate对象的queryForInt方法
- 输出结果
案例代码
// queryForInt返回一个整数
public static void test01() throws Exception {
// String sql = "SELECT COUNT(*) FROM product;";
String sql = "SELECT pid FROM product WHERE price=18888;";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
int forInt = jdbcTemplate.queryForInt(sql);
System.out.println(forInt);
}
JdbcTemplate查询-queryForMap返回一个Map集合
API介绍
public Map<String, Object> queryForMap(String sql)
执行查询语句,将一条记录放到一个Map中。
使用步骤
- 创建JdbcTemplate对象
- 编写查询的SQL语句
- 使用JdbcTemplate对象的queryForMap方法
- 处理结果
public static void test04() throws Exception {
String sql = "SELECT * FROM product WHERE pid=?;";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
Map<String, Object> map = jdbcTemplate.queryForMap(sql, 6);
System.out.println(map);
}
JdbcTemplate查询-queryForList返回一个List集合
org.springframework.jdbc.core.JdbcTemplate
类方便执行SQL语句
API介绍
public List<Map<String, Object>> queryForList(String sql)
执行查询语句,返回一个List集合,List中存放的是Map类型的数据。
使用步骤
- 创建JdbcTemplate对象
- 编写查询的SQL语句
- 使用JdbcTemplate对象的queryForList方法
- 处理结果
public static void test05() throws Exception {
String sql = "SELECT * FROM product WHERE pid<?;";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, 8);
for (Map<String, Object> map : list) {
System.out.println(map);
}
}