导包,配置数据源后即可使用
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE </version>
</dependency>
package com.CakeCN.test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTemplateTest {
@Test
//test JDBCTemplate
public void test1(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ComboPooledDataSource dataSource = (ComboPooledDataSource) app.getBean("dataSource");
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
int row = jdbcTemplate.update("insert into account values(?, ?)","tom",5000);
System.out.println(row);
}
}
当然可以直接把jdbcTemplate放进Spring容器中
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
@Test
//test JDBCTemplate
public void test1(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) app.getBean("jdbcTemplate");
int row = jdbcTemplate.update("insert into account values(?, ?)","tom",5000);
System.out.println(row);
}
jdbcTemplate中,用于增删改就直接使用jdbcTemplate.update(SQL语句)即可。而查询如下
在查询数据库时,表的每一行都应当被封装成一个对象,因此首先声明定义对象类:
对应数据库表如下
package com.CakeCN.domain;
public class Account {
private String name;
private Double money;
public void setMoney(Double money) {
this.money = money;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Account{" +
"name='" + name + '\'' +
", money=" + money +
'}';
}
}
自动封装
@Test
//test JDBCTemplate
public void test1(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) app.getBean("jdbcTemplate");
List<Account> accountList = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
System.out.println(accountList.toString());
}
查询单个值/不用封装成对象
Long sum = jdbcTemplate.queryForObject("select SUM(money) from account WHERE name=?", Long.class, "tom");
System.out.println(sum);