zoukankan      html  css  js  c++  java
  • JdbcTemplate

    一、引jar包

      spring-beans、spring-core、spring-jdbc、spring-tx。

    二、代码

    /*
    1、new JdbcTemplate(DataSource):创建JdbcTemplate对象
    2、JdbcTemplate对象方法:
        1、int update(String,Object...):执行增删改语句
        2、Map<String, Object> queryForMap(String,Object...):查询单个记录
        3、List<Map<String, Object>> queryForList(String,Object...):查询多条记录
        4、List<T> query(String,RowMapper<T>,Object...):将记录封装成JavaBean对象
            * RowMapper<T>传参方式:new BeanPropertyRowMapper<T>(T.class)
            * T属性的数据类型使用包装类型
        5、T queryForObject(String,Class<T>,Object...):常用于聚合函数查询
    */
    public class JdbctempApplication {
        private JdbcTemplate jdbcTemplate;
    
        @Before
        public void testBefore() {
            ClassLoader classLoader = JdbctempApplication.class.getClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("druid.properties");
            Properties properties = new Properties();
            DataSource dataSource = null;
            try {
                properties.load(inputStream);
                dataSource = DruidDataSourceFactory.createDataSource(properties);
            } catch (Exception e) {
                e.printStackTrace();
            }
            jdbcTemplate = new JdbcTemplate(dataSource);
        }
    
        @Test
        public void testupdate() {
            String sql = "update student set english = ? where id = ?";
            int update = jdbcTemplate.update(sql, 100, 7);
            System.out.println(update);
        }
    
        @Test
        public void testqueryformap() {
            String sql = "select * from student where id = ?";
            Map<String, Object> map = jdbcTemplate.queryForMap(sql, 7);
            System.out.println(map);
        }
    
        @Test
        public void testqueryforlist() {
            String sql = "select * from student where age > ?";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, 20);
            System.out.println(list);
        }
    
        @Test
        public void testquery() {
            String sql = "select * from student where age > ?";
            List<Student> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Student>(Student.class), 20);
            System.out.println(list);
        }
    
        @Test
        public void testqueryobject() {
            String sql = "select count(*) from student where age > ?";
            Long l = jdbcTemplate.queryForObject(sql, Long.class, 20);
            System.out.println(l);
        }
    }
  • 相关阅读:
    区块链中的密码学
    初识nodeJS
    JS或jQuery获取当前屏幕宽度
    jQuery与Zepto的异同
    使用递归解决斐波那契数列的性能问题
    sass高级语法的补充
    sass的高级语法
    栅格 CSS中的循环 媒体查询
    Zepto
    dedecms 留言板中引用模板文件方法
  • 原文地址:https://www.cnblogs.com/linding/p/13564165.html
Copyright © 2011-2022 走看看