紧接上一篇

(JdbcTemplate是线程安全的,因此可以配置一个简单的JdbcTemplate实例,将这个共享的实例注入到多个DAO类中。辅助的文档)

Spring DAO支持

http://www.cnblogs.com/Fskjb/archive/2009/11/18/1605622.html

Spring JdbcTemplate 的使用与学习

JDBCTemplate 是SPRING 框架自带的一种对sql 语句查询的封装 ,封装非常完善,虽然与Hibernate比起来有一点麻烦,但是学号JDBCTemplate可以让我们用Spirngmvc框架去代替SSH,降低了 我们的学习成本。用起来也更加方便,测试代码如下,包括执行mysql 语句,分页,调用存储过程,返回对象数组,返回整数数组,返回单个对象等


package com.tz.jdbctemplate;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.CallableStatementCreatorFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.tz.bean.User;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/applicationContext.xml")
public class TemplateTest { @Autowired
private JdbcTemplate jdbcTemplate; //明白的原理,会懂得配置,然后会懂得使用和开发,然后在深入
@Test
public void handle() throws SQLException{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("xiaoer");
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement("select * from student");
ResultSet rs = statement.executeQuery();
while(rs.next()){
System.out.println(rs.getInt("id")+"==="+rs.getString("name"));
}
rs.close();
statement.close();
connection.close();
} @Test
public void handle2(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("xiaoer");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.query("select * from student", new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
System.out.println(rs.getInt("id")+"==="+rs.getString("name"));
}
});
//hibernate
//List<Student> students = getSession().createSQLQuery("select * from student").list();
//List<Student> students = getSession().createQuery("from student").list();
} @Test
public void handle3(){
jdbcTemplate.query("select * from student", new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
System.out.println(rs.getInt("id")+"==="+rs.getString("name"));
}
});
} @Test
public void handle4(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
jdbcTemplate.query("select * from student", new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
System.out.println(rs.getInt("id")+"==="+rs.getString("name"));
}
});
} /*增加,修改,删除*/
@Test
public void handle5(){//几乎不用
//新增,修改,删除---update()
final String sql = "INSERT INTO student(name,age,male) VALUES(?,?,?)";//常量效率远远要高于普通变量
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "zhangsan");
statement.setInt(2, 100);
statement.setInt(3, 1);
return statement;
}
});
} @Test
public void handle6(){//不建议使用
//新增,修改,删除---update()
final String sql = "INSERT INTO student(name,age,male) VALUES('keke',56,1)";//常量效率远远要高于普通变量
jdbcTemplate.update(sql);
} @Test
public void handle8(){//可以使用
final String sql = "INSERT INTO student(name,age,male) VALUES(?,?,?)";//常量效率远远要高于普通变量
//PreparedStatementSetter 就是专门给所有sql语句(insert update select delete)带有?赋值的匿名内部类。
jdbcTemplate.update(sql,new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, "kekexxx");
ps.setInt(2, 587);
ps.setInt(3, 0);
}
});
}
@Test
public void handle7(){//经常使用
//新增,修改,删除---update()
final String sql = "INSERT INTO student(name,age,male) VALUES(?,?,?)";//常量效率远远要高于普通变量
jdbcTemplate.update(sql,"xxxxx",686,0);
} @Test
public void handle9(){//经常使用
final String sql = "INSERT INTO student(name,age,male) VALUES(?,?,?)";//常量效率远远要高于普通变量
Object[] params = {"mark", 16,1};
jdbcTemplate.update(sql,params,new int[]{Types.VARCHAR,Types.INTEGER,Types.INTEGER});
//jdbcTemplate.update(sql, new Object[]{"mark", 16,1},new int[]{Types.VARCHAR,Types.INTEGER,Types.INTEGER});
} //在新增的时候有时候需要返回主键
@Test
public void handle10(){
final String sql = "INSERT INTO student(name,age,male) VALUES(?,?,?)";//常量效率远远要高于普通变量
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "zhangsan");
statement.setInt(2, 100);
statement.setInt(3, 1);
return statement;
}
}, keyHolder);
//返回你新增的主键
int key = keyHolder.getKey().intValue();
System.out.println("我添加的数据返回的主键是:======"+key);
} @Test
public void handle11(){//经常使用
//新增,修改,删除---update()
final String sql = "UPDATE student SET `name`=?,age=? WHERE name=?";//常量效率远远要高于普通变量
jdbcTemplate.update(sql,"xiaoer",10,"小丑");
} @Test
public void handle12(){//经常使用
//新增,修改,删除---update()
final String sql = "delete from student where id = ?";//常量效率远远要高于普通变量
jdbcTemplate.update(sql,7);
} /*
* *************************************查询*******************************
* RowCallbackHandler:无返回值,在大数据量处理的一定使用RowCallbackHandler
* RowMapper:这个返回的是一个集合.
* 给所有的用户(100)用户发一条短信,RowCallbackHandler
* RowMapper---100万集合中--在发送
*
* jdbcTemplate.query(psc, rch);
* jdbcTemplate.query(sql, rch);
* jdbcTemplate.query(sql, pss, rch);
*
* 下面这三个是常用的
* jdbcTemplate.query(sql, rch, args);
* jdbcTemplate.query(sql, args, rch);
* jdbcTemplate.query(sql, args, argTypes, rch);
*
*/
@Test
public void handle13(){//不常用
//oracle sqlservler mysql:查询表中所有的数据的时候,数据库服务器并不会把所有的数据都都放内存中,而在通过里面数据服务器里面的默认因子去装载到内存中
//oracle ==10---io()
final String sql = "select * from student where male = ?";
final List<User> users = new ArrayList<User>();
jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 0);
return statement;
}
}, new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
users.add(user);
}
}); for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
}
} @Test
public void handle14(){//可能会使用,不建议
final String sql = "select * from student where male = 0";
final List<User> users = new ArrayList<User>();
jdbcTemplate.query(sql,new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
users.add(user);
}
}); for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
}
} @Test
public void handle16(){//可以使用,不推荐
final String sql = "select * from student where male = ?";
final List<User> users = new ArrayList<User>();
jdbcTemplate.query(sql,new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, 0);
}
},new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
users.add(user);
}
}); for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
}
} @Test
public void handle17(){//经常使用,推荐
final String sql = "select * from student where male = ?";
final List<User> users = new ArrayList<User>();
jdbcTemplate.query(sql,new Object[]{0},new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
users.add(user);
}
}); for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
}
} @Test
public void handle18(){//经常使用,推荐
final String sql = "select * from student where male = ? ";
final List<User> users = new ArrayList<User>();
jdbcTemplate.query(sql,new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
users.add(user);
}
},0); for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
}
} @Test
public void handle19(){//经常使用,推荐
final String sql = "select * from student where male = ? and age > ?";
final List<User> users = new ArrayList<User>();
jdbcTemplate.query(sql,new Object[]{0,20},new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
users.add(user);
}
}); for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
}
} @Test
public void handle21(){//经常使用,不推荐
final String sql = "select * from student where male = ? and age > ?";
final List<User> users = new ArrayList<User>();
jdbcTemplate.query(sql,new Object[]{0,20},new int[]{Types.INTEGER,Types.INTEGER},new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
users.add(user);
}
}); for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
}
} @Test
public void handle20(){//经常使用,推荐
final String sql = "select * from student where male = ? and age > ? ";
final List<User> users = new ArrayList<User>();
jdbcTemplate.query(sql,new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
users.add(user);
}
},0,20); for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
}
} /**
*
* RowMapper---100万集合中--在发送
*
* <T> List<T> jdbcTemplate.query(psc, rowMapper);
* <T> List<T>jdbcTemplate.query(sql, rowMapper);
* <T> List<T>jdbcTemplate.query(sql, pss, rowMapper);
*
* 下面这三个是常用的
* <T> List<T>jdbcTemplate.query(sql, rowMapper, args);
* <T> List<T>jdbcTemplate.query(sql, args, rowMapper);
* <T> List<T>jdbcTemplate.query(sql, args, argTypes, rowMapper);
*/
@Test
public void handle22(){//经常使用,推荐
final String sql = "select * from student where male = ? and age > ? ";
List<User> users = jdbcTemplate.query(sql,new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int index) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
return user;
}
},0,20); for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
}
} @Test
public void handle23(){//经常使用,推荐
final String sql = "select * from student where male = ? and age > ? ";
List<User> users = jdbcTemplate.query(sql,new Object[]{0,20},new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int index) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
return user;
}
}); for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
}
} //当个实体对象返回
@Test
public void handle24(){//经常使用,推荐
final String sql = "select * from student where id = ? ";
User user = jdbcTemplate.query(sql,new Object[]{8},new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int index) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
return user;
}
}).get(0);
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
} @Test
public void handle25(){//经常使用,推荐
final String sql = "select * from student where id = ? ";
final User user = new User();
jdbcTemplate.query(sql,new Object[]{8},new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
}
});
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
} @Test
public void hanle26(){
final String sql = "select * from student where id = ? ";
User user = jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("name"));
user.setAge(rs.getInt("age"));
return user;
}
},8);
System.out.println(sql);
System.out.println(user.getUserId()+"==="+user.getUsername()+"==="+user.getAge());
} @Test
public void hanle27(){
final String sql = "select * from student where id = ? ";
Map<String, Object> map = jdbcTemplate.queryForMap(sql,8);
System.out.println(map);
} //求总数(把常用的聚合函数sum,max,avg,自己去实现一次,日期,截取,替换这些常用sql要去总结和归纳)
@Test
public void handle28(){
final String sql = "SELECT count(1) from student";
jdbcTemplate.query(sql, new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
System.out.println(rs.getInt(1));
}
});
} @Test
public void test2(){
sayHello("Nio","BUKENG","robinName");
} public void sayHello(String ...names){
for (String string : names) {
System.out.println(string);
}
} /**
* int queryForInt(sql)
* int queryForInt(sql,Object...args)
* int queryForInt(sql,Object[] params,int[] types)
*
*/
@Test
public void handle29(){
//第一种方式
//final String sql = "SELECT count(1) from student where age > 30 && male = 1";
//int count = jdbcTemplate.queryForInt(sql);
final String sql = "SELECT count(1) from student where age > ? && male = ?";
int count =jdbcTemplate.queryForInt(sql,30,1);
System.out.println("count=============="+count);
int count2 = jdbcTemplate.queryForInt(sql, new Object[]{30,1},new int[]{Types.INTEGER,Types.INTEGER});
System.out.println("count2=============="+count2);
} @Test
public void handle30(){
final String sql = "SELECT count(1) from student where age > ? && male = ?";
Integer count = jdbcTemplate.queryForObject(sql, new Object[]{30,1},new RowMapper<Integer>(){
@Override
public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getInt(1);
}
});
System.out.println("================"+count);
} //求年龄大于30岁的总数和综合,和平均数
@Test
public void handle31(){
final String sql = "SELECT sum(age) as s,count(1) as c ,avg(age) from student where age > ? && male = ?"; Map<String, Object> map = jdbcTemplate.queryForObject(sql, new
Object[]{30,1},new RowMapper<Map<String, Object>>(){
@Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("sum", rs.getInt(1));
map.put("count", rs.getInt(2));
map.put("avg", rs.getInt(3));
return map;
}
});
System.out.println("================"+map);
} @Test
public void handle32(){
final String sql = "SELECT sum(age) as s,count(1) as c ,avg(age) from student where age > ? && male = ?";
Integer[] integers = jdbcTemplate.queryForObject(sql, new Object[]{30,1},new RowMapper<Integer[]>(){
@Override
public Integer[] mapRow(ResultSet rs, int rowNum) throws SQLException {
Integer[] integers = new Integer[3];
integers[0] = rs.getInt(1);
integers[1] = rs.getInt(2);
integers[2] = rs.getInt(3);
return integers;
}
});
for (Integer integer : integers) {
System.out.println("================"+integer);
}
} @Test
public void handle33(){
final String sql = "SELECT sum(age) as s,count(1) as c ,avg(age) from student where age > ? && male = ?";
Count count= jdbcTemplate.queryForObject(sql, new Object[]{30,1},new RowMapper<Count>(){
@Override
public Count mapRow(ResultSet rs, int rowNum) throws SQLException {
Count count = new Count();
count.setSum(rs.getInt(1));
count.setCount(rs.getInt(2));
count.setAvg(rs.getInt(3));
return count;
}
});
System.out.println("================"+count.getSum());
System.out.println("================"+count.getCount());
System.out.println("================"+count.getAvg());
} @Test
public void handle34() throws JSONException{
List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from student");
System.out.println(maps);
//struts2 -json-lib.jar --xwork.jar
String jsonString = JSONUtil.serialize(maps, null, null, false, true);
System.out.println(jsonString); //[{id=1, name=单晨, age=17, male=1, createtime=2014-10-19 20:39:04.0,
updatetime=null}, {id=2, name=keke, age=30, male=1,
createtime=2014-10-19 20:39:25.0, updatetime=null}, {id=3, name=赵龙,
age=22, male=1, createtime=2014-10-19 20:39:25.0, updatetime=null},
{id=4, name=白羊, age=21, male=0, createtime=2014-10-19 20:39:46.0,
updatetime=null}, {id=6, name=xiaoer, age=10, male=0,
createtime=2014-10-19 20:40:28.0, updatetime=null}, {id=8, name=keke,
age=21, male=1, createtime=2015-02-26 23:40:33.0, updatetime=null},
{id=9, name=fei, age=1, male=1, createtime=2015-02-26 23:42:03.0,
updatetime=null}, {id=10, name=zhangsan, age=100, male=1,
createtime=2015-02-26 23:45:17.0, updatetime=null}, {id=11, name=keke,
age=56, male=1, createtime=2015-02-26 23:46:37.0, updatetime=null},
{id=12, name=xxxxx, age=686, male=0, createtime=2015-02-26 23:47:59.0,
updatetime=null}, {id=13, name=kekexxx, age=587, male=0,
createtime=2015-02-26 23:53:27.0, updatetime=null}, {id=14, name=mark,
age=16, male=1, createtime=2015-02-26 23:55:58.0, updatetime=null},
{id=15, name=mark, age=16, male=1, createtime=2015-02-26 23:57:47.0,
updatetime=null}, {id=16, name=zhangsan, age=100, male=1,
createtime=2015-02-27 00:01:26.0, updatetime=null}] //[{"id":1,"name":"单
晨","age":17,"male":1,"createtime":"2014-10-19T20:39:04"},
{"id":2,"name":"keke","age":30,"male":1,"createtime":"2014-10-19T20:39:25"},
{"id":3,"name":"赵
龙","age":22,"male":1,"createtime":"2014-10-19T20:39:25"},
{"id":4,"name":"白
羊","age":21,"male":0,"createtime":"2014-10-19T20:39:46"},{"id":6,"name":"xiaoer","age":10,"male":0,"createtime":"2014-10-19T20:40:28"},{"id":8,"name":"keke","age":21,"male":1,"createtime":"2015-02-26T23:40:33"},{"id":9,"name":"fei","age":1,"male":1,"createtime":"2015-02-26T23:42:03"},{"id":10,"name":"zhangsan","age":100,"male":1,"createtime":"2015-02-26T23:45:17"},{"id":11,"name":"keke","age":56,"male":1,"createtime":"2015-02-26T23:46:37"},{"id":12,"name":"xxxxx","age":686,"male":0,"createtime":"2015-02-26T23:47:59"},{"id":13,"name":"kekexxx","age":587,"male":0,"createtime":"2015-02-26T23:53:27"},{"id":14,"name":"mark","age":16,"male":1,"createtime":"2015-02-26T23:55:58"},{"id":15,"name":"mark","age":16,"male":1,"createtime":"2015-02-26T23:57:47"},{"id":16,"name":"zhangsan","age":100,"male":1,"createtime":"2015-02-27T00:01:26"}]
} @Test
//错误
public void handle35() throws JSONException{
//如果要想支持的话,那么久和hibernate一样了。
List<Student> students = jdbcTemplate.queryForList("select * from student", Student.class);
String jsonString = JSONUtil.serialize(students, null, null, false, true);
System.out.println(jsonString); } @Test
public void handle36(){
//execute:动态创建数据库,表,索引,alert 存储过程,函数,触发器
jdbcTemplate.execute("create database keke");
} //批量处理(修改,删除,新增)为了解决大数量的导入和导出的时候,一些大批量量数据的的发送,100万发一条的短信 @Test
public void hanler37(){
jdbcTemplate.query("select * from student",new RowCallbackHandler(){
@Override
public void processRow(ResultSet rs) throws SQLException {
//给学生发送短信
}
});
} @Test
public void hanler38(){
//我要把所有的学生的名称加上一个前缀tz
final List<Student> students = new ArrayList<Student>();
jdbcTemplate.query("select * from student",new RowCallbackHandler(){
@Override
public void processRow(ResultSet rs) throws SQLException {
//给学生发送短信
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
students.add(student);
}
}); //如果牵涉到update 删除的时候一定要非常的谨慎条件十分满足。
//所有的数据删除一定要逻辑删除,而且数据库一定要每天必须一定要备份.
//服务器的IO瓶颈,
// for (Student student : students) {
// jdbcTemplate.update("update student set name=? where id = ?","tz"+student.getName(),student.getId());
// } //第一种写法
// jdbcTemplate.batchUpdate("update student set name=? where id = ?", new BatchPreparedStatementSetter() {
// @Override
// public void setValues(PreparedStatement ps, int index) throws SQLException {
// Student student = students.get(index);
// ps.setString(1, student.getName());
// ps.setInt(2, student.getId());
// }
//
// @Override
// public int getBatchSize() {
// return students.size();
// }
// }); //第二种写法
List<Object[]> objects = new ArrayList<Object[]>();
for (Student student : students) {
Object[] object = {student.getName()+"我爱你们",student.getId()};
objects.add(object);
} jdbcTemplate.batchUpdate("update student set name=? where id = ?", objects);
} //调用存储过程(单条记录和多条记录) @Test
public void handle39(){
List<SqlParameter> sqlParameters = new ArrayList<SqlParameter>();
Map<String, Object> map = jdbcTemplate.call(new CallableStatementCreator() {
@Override
public CallableStatement createCallableStatement(Connection con)
throws SQLException {
CallableStatement statement = con.prepareCall("{call keke()}");
// ResultSet rs = statement.executeQuery();
// while(rs.next()){
//
// }
return statement;
}
}, sqlParameters); System.out.println(map.get("#result-set-1"));
} @Test
public void handle40(){
List<SqlParameter> sqlParameters = new ArrayList<SqlParameter>();
final List<Student> students = new ArrayList<Student>();
jdbcTemplate.call(new CallableStatementCreator() {
@Override
public CallableStatement createCallableStatement(Connection con)
throws SQLException {
CallableStatement statement = con.prepareCall("{call keke()}");
ResultSet rs = statement.executeQuery();
Student student = null;
while(rs.next()){
student= new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
students.add(student);
}
return statement;
}
}, sqlParameters); for (Student student : students) {
System.out.println(student.getId()+"==="+student.getName());
}
} @Test
public void hanle41(){
List<SqlParameter> sqlParameters = new ArrayList<SqlParameter>();
sqlParameters.add(new SqlParameter("cage", Types.INTEGER));
sqlParameters.add(new SqlOutParameter("number", Types.INTEGER));
sqlParameters.add(new SqlOutParameter("name", Types.VARCHAR));
Map<String, Object> map = jdbcTemplate.call(new CallableStatementCreator() {
@Override
public CallableStatement createCallableStatement(Connection con)
throws SQLException {
CallableStatement statement = con.prepareCall("{call USER_RELATIONS(?,?,?)}");
statement.setInt(1, 17);
return statement;
}
}, sqlParameters); System.out.println(map.get("number"));
System.out.println(map.get("name"));
}
@Test
public void hanle42(){
CallableStatementCreatorFactory factory = new CallableStatementCreatorFactory("{call USER_RELATIONS(?,?,?)}");
factory.addParameter(new SqlParameter("cage", Types.INTEGER));
factory.addParameter(new SqlOutParameter("number", Types.INTEGER));
factory.addParameter(new SqlOutParameter("name", Types.VARCHAR));
Map<String,Integer> params = new HashMap<String, Integer>();
params.put("cage", 17);
CallableStatementCreator creator = factory.newCallableStatementCreator(params); //====================================【出异常了哦!!!!】
CallableStatementCallback; SQL [{call USER_RELATIONS(?,?,?)}]; Parameter
number 1 is not an OUT parameter; nested exception is
java.sql.SQLException: Parameter number 1 is not an OUT parameter
jdbcTemplate.execute(creator,new CallableStatementCallback<Map<String, Object>>() {
@Override
public Map<String, Object> doInCallableStatement(
CallableStatement cs) throws SQLException,
DataAccessException {
cs.execute();
Map<String,Object> map = new HashMap<String, Object>();
System.out.println(cs.getInt(2)+"========="+cs.getString(3));
return map;
}
}); } //分页 @Test
public void hanle43(){
List<User> users = findUsers("578789",10, 10);
for (User user : users) {
System.out.println(user.getUserId()+"==="+user.getUsername());
}
} public List<User> findUsers(String password,int pageNo,int pageSize){
String sql = "select * from user where 1=1 ";
String countSql ="select count(1) from user where 1=1 ";
if(password!=null){
sql+=" and password = '"+password+"'";
countSql+=" and password = '"+password+"' ";
}
System.out.println(countSql);
List<User> users = jdbcTemplate.query(sql+" limit ?,?", new RowMapper<User>(){
@Override
public User mapRow(ResultSet rs, int index) throws SQLException {
User user = new User();
user.setUserId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
return user;
}
},pageNo,pageSize); Integer totalCount = jdbcTemplate.queryForObject(countSql,Integer.class);
System.out.println("总页数是:"+totalCount);
return users;
} }
好文要顶
关注我
收藏该文

0
0
(请您对文章做出评价)

« 上一篇:Hibernate 的事物简单的增删查改
» 下一篇:连接池的工作机制

Spring JdbcTemplate 的使用与学习(转)的更多相关文章

  1. Spring JdbcTemplate 与 事务管理 学习

    Spring的JDBC框架能够承担资源管理和异常处理的工作,从而简化我们的JDBC代码, 让我们只需编写从数据库读写数据所必需的代码.Spring把数据访问的样板代码隐藏到模板类之下, 结合Sprin ...

  2. Spring JdbcTemplate 的使用与学习

    JDBCTemplate 是SPRING 框架自带的一种对sql 语句查询的封装 ,封装非常完善,虽然与Hibernate比起来有一点麻烦,但是学号JDBCTemplate可以让我们用Spirngmv ...

  3. spring jdbcTemplate源码剖析

    本文浅析 spring jdbcTemplate 源码,主要是学习其设计精髓.模板模式.巧妙的回调 一.jdbcTemplate 类结构 ①.JdbcOperations : 接口定义了方法,如 &l ...

  4. 【Spring】Spring的数据库开发 - 2、Spring JdbcTemplate的常用方法(execute、update、query)

    Spring JdbcTemplate的常用方法 文章目录 Spring JdbcTemplate的常用方法 execute() update() query() 简单记录-Java EE企业级应用开 ...

  5. (转)Spring JdbcTemplate 方法详解

    Spring JdbcTemplate方法详解 文章来源:http://blog.csdn.net/dyllove98/article/details/7772463 JdbcTemplate主要提供 ...

  6. [转]Spring JdbcTemplate 查询分页

    原文:http://blog.csdn.net/xiaofanku/article/details/4280128 现在进行的项目由于数据库的遗留原因(设计的不堪入目)不能用hibernate.所以用 ...

  7. Spring 4 官方文档学习(十二)View技术

    关键词:view technology.template.template engine.markup.内容较多,按需查用即可. 介绍 Thymeleaf Groovy Markup Template ...

  8. Spring 4 官方文档学习(十一)Web MVC 框架之配置Spring MVC

    内容列表: 启用MVC Java config 或 MVC XML namespace 修改已提供的配置 类型转换和格式化 校验 拦截器 内容协商 View Controllers View Reso ...

  9. spring jdbcTemplate query

    1. spring jdbcTemplate query需要实现mapRow方法 package com.cdv.apolloagent.jdbc.dao.impl; import java.sql. ...

随机推荐

  1. Java虚拟机详解05----垃圾收集器及GC参数

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  2. Linux压力测试工具Tsung安装、使用和图形报表生成

    简介 Tsung 是一个压力测试工具,可以测试包括HTTP, WebDAV, PostgreSQL, MySQL, LDAP, and XMPP/Jabber等服务器.针对 HTTP 测试,Tsung ...

  3. unix文件操作函数

    1. fopen函数 #include <stdio.h> FILE *fopen(const char *path, const char *mode) 返回:文件顺利打开后,指向该流的 ...

  4. ios--Attributes和ParagraphStyle介绍

    NSMutableParagraphStyle的部分属性: typedef NS_ENUM(NSInteger, NSLineBreakMode) {/* What to do with long l ...

  5. kprobe原理解析(一)

    kprobe是linux内核的一个重要特性,是一个轻量级的内核调试工具,同时它又是其他一些更高级的内核调试工具(比如perf和systemtap)的“基础设施”,4.0版本的内核中,强大的eBPF特性 ...

  6. C# 将透明图片的非透明区域转换成Region

    以下代码实现将一张带透明度的png图片的非透明部分转换成Region输出 /// <summary> /// 根据图片得到一个图片非透明部分的区域 /// </summary> ...

  7. Delphi7 安装ICS,与简单使用

    官网 http://www.overbyte.be/ 下载 OverbyteIcsV816 完成后解压到E:\Delphi7\OverbyteIcsV816\ 1.在library里加入E:\Delp ...

  8. matlab取消和添加注释以及一些快捷键

    1 matlab中关于注释: 多行注释: 选中要注释的若干语句,工具栏菜单Text->Comment,或者鼠标右击选"Comment",或者快捷键Ctrl+R 取消注释: 选 ...

  9. 解决vs2013使用Git推送到远程仓库报错的问题

    在上一篇<让PowerShell使用Git>中可以让PowerShell运行Git命令,那么就开始使用. 1.从远程仓库克隆项目 GitHub和Git.oschina都是不错的免费托管网站 ...

  10. Linux 常用工具贴

    1. nmon for Linux  用于监控Linux CPU.IO.网络等,可以生产excel格式的报表  http://nmon.sourceforge.net/pmwiki.php?n=Sit ...