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 //Liststudents = getSession().createSQLQuery("select * from student").list(); //List 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 users = new ArrayList (); 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 users = new ArrayList (); 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 users = new ArrayList (); 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 users = new ArrayList (); 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 users = new ArrayList (); 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 users = new ArrayList (); 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 users = new ArrayList (); 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 users = new ArrayList (); 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万集合中--在发送 * * List jdbcTemplate.query(psc, rowMapper); * List jdbcTemplate.query(sql, rowMapper); * List jdbcTemplate.query(sql, pss, rowMapper); * * 下面这三个是常用的 * List jdbcTemplate.query(sql, rowMapper, args); * List jdbcTemplate.query(sql, args, rowMapper); * List jdbcTemplate.query(sql, args, argTypes, rowMapper); */ @Test public void handle22(){ //经常使用,推荐 final String sql = "select * from student where male = ? and age > ? "; List users = jdbcTemplate.query(sql,new RowMapper () { @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 users = jdbcTemplate.query(sql,new Object[]{0,20},new RowMapper () { @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 () { @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 () { @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 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 (){ @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 map = jdbcTemplate.queryForObject(sql, new Object[]{30,1},new RowMapper