Spring 温习笔记(五)springjdbcTemplate基本使用
什么是springjdbcTemplate
springjdbcTemplate 是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。通常我们可以理解其为操作jdbc的一个强大工具,
如何使用springjdbcTemplate
首先需要建立依赖库,即导入jar包坐标
mysql
mysql-connector-java
5.1.32
com.mchange
c3p0
0.9.5.2
com.alibaba
druid
1.1.10
com.twelvemonkeys.common
common-io
3.4.1
commons-fileupload
commons-fileupload
1.3.3
org.springframework
spring-jdbc
5.1.9.RELEASE
org.springframework
spring-tx
5.1.9.RELEASE
org.springframework
spring-context
5.1.10.RELEASE
junit
junit
4.12
org.aspectj
aspectjweaver
1.9.0
org.springframework
spring-test
5.1.10.RELEASE
数据库配置文件
c3p0.driverDriver=com.mysql.jdbc.Driver
c3p0.url=jdbc//localhost:3306/test
c3p0.user=root
c3p0.password=root
c3p0.initialSize=5
c3p0.maxActive=10
c3p0.maxWait=3000编写xml配置文件
<?xml version=”1.0” encoding=”UTF-8”?>
account类
public class Account {
private String name;
private double balance;
public Account() {
}
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"name='" + name + '\'' +
", balance=" + balance +
'}';
}
}
test类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JDBC01Test {
//@Resource(name = "jdbcTemplate")
@Autowired
@Qualifier("jdbcTemplate")
JdbcTemplate jdbcTemplate = new JdbcTemplate();
@Test
public void test01(){
String sql = "insert into account(name,balance) values (?,?) ";
jdbcTemplate.update(sql,"jack",9000);
System.out.println(jdbcTemplate);
}
@Test
public void test02(){
String sql = "update account set balance = ? where name = ? ";
int row = jdbcTemplate.update(sql, 100000, "tom");
System.out.println(row);
}
@Test
public void test03(){
String sql = "delete from account where name = ? ";
int row = jdbcTemplate.update(sql, "jack");
System.out.println(row);
}
@Test
public void test04(){
String sql = "select * from account ";
List<Account> query = jdbcTemplate.query(sql,
new BeanPropertyRowMapper<Account>(Account.class));
System.out.println(query);
}
@Test
public void test05(){
String sql = " select * from account where name = ?";
Account account = jdbcTemplate.queryForObject(sql,
new BeanPropertyRowMapper<Account>(Account.class), "tom");
System.out.println(account);
}
@Test
public void test06(){
String sql = " select count(*) from account ";
Long count = jdbcTemplate.queryForObject(sql, long.class);
System.out.println(count);
}
}
经测试上述功能完美运行,springjdbcTemplate完美运行。
还没有评论,来说两句吧...