Spring JdbcTemplate基本使用
JdbcTemplate开发步骤
导入spring-jdbc和spring-tx坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.17</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.17</version>
</dependency>
创建数据库表和实体
创建JdbcTemplate对象
<!-- 数据源对象-->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/tset"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- jdbc模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
执行数据库操作
public void test2() throws Exception{
ApplicationContext app = new ClassPathXmlApplicationContext("spring-mvc.xml");
JdbcTemplate jdbcTemplate = app.getBean(JdbcTemplate.class);
// 插入
int row = jdbcTemplate.update("insert into account values (?,?)","张三",8000);
// 更新
jdbcTemplate.update("update account set name = ? where name = ?","Tom","王五");
// 删除
jdbcTemplate.update("delete from account where name = ?" ,"李四");
// 单值查询
Account account = jdbcTemplate.queryForObject("select money from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), "张三");
//全表查询
List<Account> accountList = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
//
Long aLong = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
System.out.println(aLong);
System.out.println(account);
System.out.println(accountList);
}