Article Directory
〇, write in front
JdbcTemplate
Depends on the database connection pool, if there is no corresponding knowledge reserve, please click these words to learn firstDruid数据库连接池
JdbcTemplate
For 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 Druid
configuration file to change the connection to the database url
:
url=jdbc:mysql://localhost:3306/db1?serverTimezone=GMT
Use Junit
every method written in the test
One, modify operation
Requirements: modification id
to 1
the balance
field 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=3
records
@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 JdbcTemplate
object, 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