目录
【query方法】返回结果是list,且list中元素必须是自定义bean;
【update方法】:用于 增加、删除、修改操作(返回的值是受影响行数)
2.queryForObject(多个键值对封装成一个List集合进行查询)
1、什么是JdbcTemplate
它是 Spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。通过这个类可以让我们对于JDBC的使用游刃有余。并且JdbcTemplate处理了资源的建立和释放,它也能帮助我们避免一些常见的错误,比如忘了总要关闭连接。除了JdbcTemplate,spring 框架还为我们提供了很多的操作模板类。
2、JdbcTemplate的常用方法
1、execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
Execute、executeQuery、executeUpdate
2、update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句 SQL SERVCER(GO SQL语句 GO) ;
3、query方法及queryForXXX方法:用于执行查询相关语句;
4、call方法:用于执行存储过程、函数相关语句。
最常用方法:
【queryForObject】查询出一条记录并封装到一个对象中。可以返回的是String、Integer、Double或者自定义bean。但是如果查询的记录为0条或者大于1条,对不起抛出异常。(小本本记好)
【query方法】返回结果是list,且list中元素必须是自定义bean;
【update方法】:用于 增加、删除、修改操作(返回的值是受影响行数)
3、具体实例
增加、删除、修改(具体操作基本一致)
String sql="insert into team(tname,location) value (?,?)"; return this.getJdbcTemplate().update(sql,team.getName(),team.getLocation());
查询分如下几种情况
单值查询
1.不需要填充参数的单值查询
//查询队伍中有多少只队伍(tid唯一) String sql="select count(tid) from team"; return this.getJdbcTemplate().queryForObject(sql,Integer.class);//Integer.class表示返回值类型
2.填充参数
//SQL_LOGIN = "SELECT ID FROM EADMIN WHERE USERNAME=? AND PASSWORD=?"; public boolean login(String username, String password) { Integer i = this.getJdbcTemplate().queryForObject(SQL_LOGIN,new Object[]{username,password},Integer.class); if (i!=null) return true; else return false; }
键值对查询
1.queryForMap(单个键值对)
String sql="select max(tid),min(tid) from team"; return this.getJdbcTemplate().queryForMap(sql);
2.queryForObject(多个键值对封装成一个List集合进行查询)
public List<Map<String, Integer>> console() { ArrayList<Map<String, Integer>> data11 = new ArrayList<>(); data11 = this.getJdbcTemplate().queryForObject(SQL_CONSOLE_EXPRESSER, new RowMapper<ArrayList<Map<String, Integer>>>() { @Override public ArrayList<Map<String, Integer>> mapRow(ResultSet resultSet, int i) throws SQLException { ArrayList<Map<String, Integer>> data = new ArrayList<>(); int data_size = resultSet.getInt("data_size"); int data_day = resultSet.getInt("data_day"); Map data1 = new HashMap(); data1.put("data_size", data_size); data1.put("data_day", data_day); data.add(data1); return data; } }); return data11;}
成员列表查询(query)
1.不需要填充参数
String sql="select * from team where"; return this.getJdbcTemplate().query(sql, new RowMapper<Team>() { @Override public Team mapRow(ResultSet resultSet, int i) throws SQLException { Team team=new Team(); team.setId(resultSet.getInt("tid")); team.setName(resultSet.getString("tname")); team.setLocation(resultSet.getString("location")); return team; } });
2.填充参数
public List<Expresser> findAll(int limit, int offset, int pageNum) { return this.getJdbcTemplate().query(SQL_FIND,new Object[]{offset,pageNum}, new RowMapper<Expresser>() { @Override public Expresser mapRow(ResultSet resultSet, int i) throws SQLException { return hasResultset(resultSet); } });}