- 小编最近一直在整理自己以前用过学过的知识,所以有时候重点没有这么标明,所以最近补了一些 JdbcTemplate最常用的几种方法。下面这些方法我会一一演示给大家看的,希望对你有用。
这个方法是过时的,count就是数据库里面有多少条信息,返回结果是int类型
public class Demo08 {
//queryForInt
@Test
public void test01(){
JdbcTemplate template = new JdbcTemplate(DataSourceUtils.getDataSource());
*//查询有点少条数据信息。*
String sql = "SELECT COUNT(*) FROM product ;";
***//打印出结果,看看库里面插入了几条信息***
System.out.println("count : "+ template.queryForInt(sql));
}
这个方法也是过时的,count就是数据库里面有多少条信息,返回结果是long类型
//queryForLong
@Test
public void test02(){
JdbcTemplate template = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "SELECT COUNT(*) FROM product;";
*//查询有点少条数据信息。*
long count = template.queryForLong(sql);
System.out.println("count: " + count);
}
通过id查看数据库里面和id所对应的值,例如 id=8 name=张三 通过8就可以查找到张三
//queryForObjexct********
@Test
public void test03(){
JdbcTemplate template =new JdbcTemplate(DataSourceUtils.getDataSource());
//通过id查看数据库里面和id所对应的值
String sql = "SELECT Pname FROM product WHERE id = ?;";
String str = template.queryForObject(sql,String.class,8);
//打印结果
System.out.println("str:"+str);
}
注意里面有个map集合,这里面是通过id查找一条数据库信息。例如:
{id=8, name=张三}
//queryForMap
@Test
public void test04(){
JdbcTemplate template = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "SELECT * FROM product WHERE id = ?;";
//通过id查找一条数据库信息
Map<String, Object> map = template.queryForMap(sql, 8);
System.out.println(map);
}
这个方法与test04有点不一样,这个方法也是通过id查询到一条信息并存到map集合里面,同时也用了一个list集合将每个map集合保存起来,从而实现存储一个表所有的数据。这样就可以打印一个表里面所有的信息了。
product是一个实例类,这里面的用途是将map集合的信息对应着product里面成员变量。
//queryForList
@Test
public void test05(){
JdbcTemplate template = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "SELECT * FROM product WHERE id < ?;";
List<Product> query = template.query(sql, new RowMapper<Product>() {
@Override
public Product mapRow(ResultSet resultSet, int i) throws SQLException {
int id = resultSet.getInt("id");
String pname = resultSet.getString("name");
//创建Product对象
Product p = new Product(id,name);
return p;
}
},12);
//遍历集合
for (Product p : query) {
System.out.println(p);
}
}
重点:通过template.query查找id小于10的数据,这种比上面那种更加简单,
其实template.query的原理就是上面一样,小编看了一下,研究了出来。
// BeanPropertyRowMapper *****
@Test
public void test06(){
JdbcTemplate template = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "SELECT * FROM product WHERE id < ?;";
List<Product> List = template.query(sql,new BeanPropertyRowMapper<>(Product.class),10);
//forEach遍历数据
for (Product p : List) {
System.out.println(p);
}
}
}
重点:通过template.queryForObject查询一条数据库语句
//创建模板对象
private JdbcTemplate template = new
JdbcTemplate(DataSourceUtils.getDataSource());
/*
通过用户名和密码查询用户,如果找到返回user对象,否侧返回null
*/
public User findUser(String username,String password){
//使用queryForObject查询1条结果:如果没有找到记录,抛出异常
try{
return template.queryForObject("select * from user where username=? and password=?",
new BeanPropertyRowMapper<>(User.class),username,password);
}catch (DataAccessException e){
return null;//表示没有找到记录
}
}