JdbcTemplate performs DML addition, deletion and modification operations


〇, write in front

JdbcTemplateDepends on the database connection pool, if there is no corresponding knowledge reserve, please click these words to learn firstDruid数据库连接池

JdbcTemplateFor related jar包download and use steps, please click on these texts to download and learn to use it simply

Create a database, create a table, add a few records

create database db1;
use db1;
create table account(
	id int primary key auto_increment,
	name varchar(32),
	balance double
);
insert into account values
(null,'zhangsan',1000),
(null,'lisi',2500);

Go to the Druidconfiguration file to change the connection to the database url:

url=jdbc:mysql://localhost:3306/db1?serverTimezone=GMT

Use Junitevery method written in the test

One, modify operation

Requirements: modification idto 1the balancefield for the 4500

    @Test
    public void test1() {
    
    
   	 	JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
        String sql = "update account set balance = ? where id = ?";
        int cnt = template.update(sql,4500, 1);
        System.out.println(cnt);
    }

Two, add operation

Requirements: add a record

    @Test
    public void test2(){
    
    
    	JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
        String sql = "insert into account values(null,?,?)";
        int cnt = template.update(sql,"wangsan",100);
        System.out.println(cnt);
    }

Three, delete operation

Requirements: deleted id=3records

    @Test
    public void test3(){
    
    
   		JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
        String sql = "delete from account where id = ?";
        int cnt = template.update(sql, 5);
        System.out.println(cnt);
    }

It can be found that the above three pieces of code have similar operations:

JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

To obtain the JdbcTemplateobject, you can extract this code into the class and define it as a private variable:

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

In this way, if you write code in this class later, you can omit these steps and use it directly


JdbcTemplate performs DQL query operations

Guess you like

Origin blog.csdn.net/lesileqin/article/details/112470234