JDBCTemplate的用法

上面几篇博客就讲述了Java如何连接数据库,和Java中操作数据库的工具类以及Druid连接池,接下来说一说JDBCTemplate的用法。

其实JDBCTemplate是对上面所有方法的一个封装,这样便于我们个更好的简化我们的代码,一起来看看吧!、

JDBCTemplate的具体用法

首先应该导入具体的jar包,这一步可能需要你到百度上去搜了,我也是搜了一会才找到的

然后我们就可以用我们的模板了

package JDBCTemplate;

import Util.DruidUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

public class JDBCTemplate {
    public static void main(String[] args) {
        //创建JdbcTemplate对象。

        JdbcTemplate template  = new JdbcTemplate(DruidUtil.getDataSource());
        //执行增删改语句的  函数是update
        String sql = "insert into goods(name,value)values('洋葱',34)";
        int update = template.update(sql);

        System.out.println(update);

        //执行数据库的查询操作
        String sql = "select * from goods";
        List<Map<String, Object>> maps = template.queryForList(sql);
        System.out.println(maps);

        //易错点,利用queryforMap的结果只能是一条结果  不能多条结果
//        Map<String, Object> stringObjectMap = template.queryForMap(sql);
//        System.out.println(stringObjectMap);

        //将数据存入类中,便于数据的传输和存储
        List<Goods> query = template.query(sql, new BeanPropertyRowMapper<Goods>(Goods.class));
        for (Goods g: query){
            System.out.println(g);
        }


    }

}

Goods类:

package JDBCTemplate;

public class Goods {
    Integer id;
    String name;
    Integer value;

    public Goods(Integer id, String name, Integer value) {

        this.id = id;
        this.name = name;
        this.value = value;
    }
    public Goods(){

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getValue() {
        return value;
    }

    public void setValue(Integer value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", value=" + value +
                '}';
    }
}

上面就是具体的操作方式,最常用的也就是将我们得到数据封装到一个对象中,然后我们就可以用对象来进行数据传输,完成在Web中数据的显示! 

猜你喜欢

转载自blog.csdn.net/yanzhiguo98/article/details/89034364
今日推荐