SpringTemplate用法示例

需要包:
commons-logging-1.2.jar
spring-beans-5.0.0.RELEASE.jar
spring-core-5.0.0.RELEASE.jar
spring-jdbc-5.0.0.RELEASE.jar
spring-tx-5.0.0.RELEASE.jar

package springtemplate;

import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;

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

public class Demo1SpringTemplate {
    JdbcTemplate template = new JdbcTemplate(C3P0xmlUtils.getDatesource());


    @Test
    public void test01() {
        //        1  导包
//        2 创建JDBCTemplate对象  依赖数据源DataSource
        JdbcTemplate template = new JdbcTemplate(C3P0xmlUtils.getDatesource());
        //   JdbcTemplate template = new JdbcTemplate(C3P0xmlUtils.getDataSource());
//        3 调用JDBCTemplate方法来完成CRUD操作
        int zh = template.update("INSERT into users values (?,?,?)", null, "张ba", "1111");
        System.out.println(zh+"数据添加成功");
    }

    @Test
    // 查询 pid为11的记录  将其封装MAP 集合  只能查一条
    public void  test02(){
        //获得DBCTemplate对象
        JdbcTemplate template = new JdbcTemplate(C3P0xmlUtils.getDatesource());
        String sql="select * from users where cid=?";
        Map<String, Object> s = template.queryForMap(sql, 2);
        System.out.println(s);
    }


    @Test
    // 查询所有
    public void  test03(){
        String sql="select * from users";
        List<Map<String, Object>> ma = template.queryForList(sql);

        for (Map<String, Object> a:ma){
            System.out.println(a);
        }

    }


    @Test
    //查询总记录数
    public void  test04(){
        String sql="select count(pname) from users";
        Long aLong = template.queryForObject(sql, long.class);
        System.out.println(aLong);
    }
    }

猜你喜欢

转载自blog.csdn.net/qq_45112637/article/details/91967294