1 package cn.zmh.PingCe; 2 3 import org.junit.Test; 4 import org.springframework.jdbc.core.BeanPropertyRowMapper; 5 import org.springframework.jdbc.core.JdbcTemplate; 6 7 import java.util.List; 8 import java.util.Map; 9 /** 10 * Spring框架 JdbcTemplate類 11 * */ 12 public class Demo { 13 //Junit單元測試,可以讓方法獨立執行 @Test 14 // 獲取JdbcTemplate對象 連接池 15 JdbcTemplate temp = new JdbcTemplate(JdbcUtils.getDataSource()); 16 17 //1. 修改1005號數據的 salary 為 10000 18 @Test 19 public void Test1(){ 20 //定義sql語句 21 String sql = "update emp set salary=10000 where id=1005"; 22 // 執行sql語句 23 int i = temp.update(sql); 24 System.out.println(i); 25 } 26 27 //2. 添加一條記錄 28 @Test 29 public void test2(){ 30 String sql = "insert into emp (id,ename,salary) values (1015,'碼雲',200)"; 31 int i = temp.update(sql); 32 System.out.println(i); 33 } 34 35 //3. 刪除最后一條的記錄 36 @Test 37 public void test3(){ 38 String sql = "delete from emp where id=?"; 39 int i = temp.update(sql, 1015); 40 System.out.println(i); 41 } 42 43 //4. 查詢id為1的記錄,將其封裝為Map集合 44 @Test 45 public void test4(){ 46 String sql = "select * from emp where id=1001"; 47 Map<String, Object> map = temp.queryForMap(sql); 48 System.out.println(map); 49 } 50 51 //5. 查詢所有記錄,將其封裝為List 52 @Test 53 public void test5(){ 54 String sql = "select * from emp"; 55 List<Map<String, Object>> maps = temp.queryForList(sql); 56 for(Map<String ,Object> m:maps){ 57 System.out.println(m); 58 } 59 } 60 61 //6. 查詢所有記錄,將其封裝為Emp對象的List集合 62 @Test 63 public void test6(){ 64 String sql = "select * from emp"; 65 List<Emp> list = temp.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class)); 66 for(Emp e:list){ 67 System.out.println(e); 68 } 69 } 70 71 //7. 查詢總記錄數 72 @Test 73 public void test7(){ 74 String sql = "select count(id) from emp"; 75 List<Map<String, Object>> maps = temp.queryForList(sql); 76 System.out.println(maps); 77 } 78 79 //7_1. 查詢總記錄數 80 @Test 81 public void test7_1(){ 82 String sql = "select count(id) from emp"; 83 Long aLong = temp.queryForObject(sql, long.class); 84 System.out.println(aLong); 85 } 86 }
