针对数据库的操作,Spring框架提供了JdbcTemplate类,该类是Spring框架数据抽象层的基础。可以说,JdbcTemplate类是Spring JDBC的核心类。
在JdbcTemplate核心类中,提供了大量的更新和查询数据库的方法,我们就是使用的这些方法来操作数据库的。
主要方法:
execute()
execute(String sql)方法可用于执行sql语句
update()
update()用于执行插入、更新和删除操作
query()
query()用于执行数据查询操作
update常用方法:
int update(String sql) 该方法是最简单的update方法重载形式你,直接执行传入的sql语句,并返回受影响的行数
int update(PreparedStatementCreator psc) 该方法执行从 PreparedStatementCreator 返回的语句,并返回受影响的行数
int update(String sql,PreparedStatementSetter pss) 该方法通过PreparedStatementSetter设置Sql语句的参数,并返回受影响的行数
int update(String sql,Object ....args) 该方法使用Object 设置SQL中的参数,要求参数不能为NULL,并返回受影响的行数
实例:
// 更新账户
public int updateAccount(Account account) {
// 定义SQL
String sql = "update account set username=?,balance=? where id = ?";
// 定义数组来存放SQL语句中的参数
Object[] params = new Object[] {
account.getUsername(),
account.getBalance(),
account.getId()
};
// 执行添加操作,返回的是受SQL语句影响的记录条数
int num = this.jdbcTemplate.update(sql, params);
return num;
}
// 删除账户
public int deleteAccount(int id) {
// 定义SQL
String sql = "delete from account where id = ? ";
// 执行添加操作,返回的是受SQL语句影响的记录条数
int num = this.jdbcTemplate.update(sql, id);
return num;
}
// 通过id查询账户数据信息
public Account findAccountById(int id) {
//定义SQL语句
String sql = "select * from account where id = ?";
// 创建一个新的BeanPropertyRowMapper对象
RowMapper<Account> rowMapper =
new BeanPropertyRowMapper<Account>(Account.class);
// 将id绑定到SQL语句中,并通过RowMapper返回一个Object类型的单行记录
return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
}
// 查询所有账户信息
public List<Account> findAllAccount() {
// 定义SQL语句
String sql = "select * from account";
// 创建一个新的BeanPropertyRowMapper对象
RowMapper<Account> rowMapper =
new BeanPropertyRowMapper<Account>(Account.class);
// 执行静态的SQL查询,并通过RowMapper返回结果
return this.jdbcTemplate.query(sql, rowMapper);
}
aplicationContext.xml
<!-- 1配置数据源 -->
<bean id="dataSource" class=
"org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--数据库驱动 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<!--连接数据库的url -->
<property name="url" value="jdbc:mysql://localhost:3306/spring" />
<!--连接数据库的用户名 -->
<property name="username" value="root" />
<!--连接数据库的密码 -->
<property name="password" value="root" />
</bean>
<!-- 2配置JDBC模板 -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 默认必须使用数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!--定义id为accountDao的Bean-->
<bean id="accountDao" class="com.jdbc.AccountDaoImpl">
<!-- 将jdbcTemplate注入到accountDao实例中 -->
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>