JdbcTemplate tool class

JdbcTemplate tool class

Note: Use the pom.xml file of the maven project to add dependencies

  1. Necessary jar package dependencies for using jdbcTemplate tool class
<dependency>
    <groupId>cn.danielw</groupId>
    <artifactId>spring-jdbc-template</artifactId>
    <version>0.2.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId><!-- 因为使用了JDBCUtils工具类,使用到了Druid类-->
    <version>1.2.4</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
    <scope>runtime</scope>
</dependency>		
  1. Commonly used methods of JdbcTemplate.class

Note: JdbcTemplate.class does not need to manually release resources, it will automatically release resources and return the connection object to the connection pool

  1. update(): Execute DML statement, that is, add, delete, modify, and return int type
@Test
public void update(){
     
     
    String sql = "update student set sage=20 where sno = ?";
    int i = temp.update(sql, 201215121);//指定参数,不需要双引号
    System.out.println();
}
  1. queryForMap(): Encapsulate the query result into a Map set, use the database column name as the key and the value as the value, and encapsulate this record into a map set

Note: The length of the result set of this method query can only be 1. That is, you can only query sql statements that return one record.

@Test
public void queryForMap(){
     
     
    String sql = "select * from student where sno = ?";
    Map<String, Object> map = temp.queryForMap(sql, 201215121);
    System.out.println(map);
}

//当sql语句执行返回结果是两条记录时,会报错
//org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 2
  1. queryForList(): The query result is encapsulated into a List collection

Note: encapsulate each record into a Map collection, and encapsulate the Map collection into a List collection: List<Map<String, Object>>

    @Test
    public void queryForList(){
     
     
        String sql = "select * from student limit 5";
        List<Map<String, Object>> mapList = temp.queryForList(sql);
        for (Map<String, Object> stringObjectMap : mapList) {
     
     
            System.out.println(stringObjectMap);
        }
    }
  1. query(): Execute the query sql and encapsulate the result into a JavaBean object

Note: the parameter of query(): RowMapper

  • Generally, we use the BeanPropertyRowMapper implementation class to complete the encapsulation of data to JavaBean
  • new BeanBeanPropertyRowMapper<type>(type.class). Type is the type of JavaBean to be encapsulated
  • The JavaBean class must be a reference type variable (Integer...), not a common type variable (int...)
  • See the example code below for details
@Test
public void query(){
     
     
    String sql = "select * from student limit 5";
    List<Student> studentList = temp.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
    for (Student student : studentList) {
     
     
        System.out.println(student);
    }
}
//List<Student> studentList = 
//temp.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
//BeanPropertyRowMapper中的参数写法一定要记忆
  1. queryForObject(): query results, encapsulate the results into objects

Note: Generally, this method is suitable for the case where the SQL statement is an aggregate function.

  • The return value is of type Lang
  • The second parameter type is: Lang.class such as:
	@Test
    public void queryForObject(){
      
      
        String sql = "select count(sno) from student";
        Long count = temp.queryForObject(sql, Long.class);
        System.out.println(count);
    }
//Long count = temp.queryForObject(sql, Long.class);
  1. JdbcTemplate test class complete code
package zhi.itlearn;

import cn.danielw.spring.jdbc.JdbcTemplate;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import zhi.itlearn.domain.Student;

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

public class JdbcTemplateTest1 {
     
     
	//将JdbcTemplate对象定义在方法外,简化代码
    //JdbcTemplate类实例化方式:new JdbcTemplate(JDBCUtils.getDateSource())
    //参数是:获得连接池对象,在此使用的是自定义的JDBCUtils工具类
    private static JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDateSource());

    @Test
    public void update(){
     
     
        String sql = "update student set sage=20 where sno = ?";
        int i = temp.update(sql, 201215121);//指定参数,不需要双引号
        System.out.println();
    }
    @Test
    public void queryForMap(){
     
     
        String sql = "select * from student where sno = ? ";
        Map<String, Object> map = temp.queryForMap(sql, 201215121);
        System.out.println(map);
    }

    @Test
    public void queryForList(){
     
     
        String sql = "select * from student limit 5";
        List<Map<String, Object>> mapList = temp.queryForList(sql);
        for (Map<String, Object> stringObjectMap : mapList) {
     
     
            System.out.println(stringObjectMap);
        }
    }

    @Test
    public void query(){
     
     
        String sql = "select * from student limit 5";
        List<Student> studentList = temp.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
        for (Student student : studentList) {
     
     
            System.out.println(student);
        }
    }
    @Test
    public void queryForObject(){
     
     
        String sql = "select count(sno) from student";
        Long count = temp.queryForObject(sql, Long.class);
        System.out.println(count);
    }
}
  1. JDBCUtils tool class
package zhi.itlearn;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
     
     
    private static DataSource ds;

    static {
     
     
        try {
     
     
            //加载配置文件
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("duril-config.properties"));
            //获得DataSource连接池对象
            //使用Druid工具类中DruidDataSourceFactory类获得连接池对象【重点】
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
     
     
            e.printStackTrace();
        } catch (Exception e) {
     
     
            e.printStackTrace();
        }
    }

    public static DataSource getDateSource(){
     
     
        return ds;
    }

    public static Connection getConnection() throws SQLException {
     
     
        return ds.getConnection();
    }

    public static void close(Statement stat,Connection conn){
     
     
        close(null,stat,conn);
    }
    public static void close(ResultSet rs, Statement stat, Connection conn){
     
     
        if (rs!=null){
     
     
            try {
     
     
                rs.close();
            } catch (SQLException e) {
     
     
                e.printStackTrace();
            }
        }
        if (stat!=null){
     
     
            try {
     
     
                stat.close();
            } catch (SQLException e) {
     
     
                e.printStackTrace();
            }
        }
        if (conn!=null){
     
     
            try {
     
     
                conn.close(); //归还连接
            } catch (SQLException e) {
     
     
                e.printStackTrace();
            }
        }
    }

}
  1. properties configuration file (druid-config.properties)
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/xskc
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000

Guess you like

Origin blog.csdn.net/qq_42278320/article/details/113006040