JdbcTemplate的使用

 1         // JDBC模板依赖于连接池来获得数据的连接,所以必须先要构造连接池
 2         DriverManagerDataSource dataSource = new DriverManagerDataSource();
 3         dataSource.setDriverClassName("com.mysql.jdbc.Driver");
 4         dataSource.setUrl("jdbc:mysql://localhost:3306/base_db?useUnicode=true&characterEncoding=UTF-8");
 5         dataSource.setUsername("root");
 6         dataSource.setPassword("123456");
 7         // 创建JDBC模板
 8         JdbcTemplate baseJt = new JdbcTemplate();
 9         // 这里也可以使用构造方法
10         jdbcTemplate.setDataSource(dataSource);
11 
12         //1.查询列表
13         List<String> list = jdbcTemplate.query("select id from tbl_day order by id desc", new RowMapper<String>(){
14             @Override
15             public String mapRow(ResultSet rs, int rowNum) throws SQLException {
16                 return rs.getString("id");
17             }
18         });
19         //2.查询对象
20         Long num = (long) jdbcTemplate.queryForObject("select count(1) from tbl_day",Long.class);
21         //3.数据操纵语言DML(insert,update,delete)
22         jdbcTemplate.update("insert into b_day(id) values('2018-10-01')");
23                     

 

posted @ 2018-10-08 11:12  一笑(ಡωಡ)难忘  阅读(223)  评论(0)    收藏  举报