Spring的模板:JdbcTemplate

本文介绍如何在Spring框架中配置DBCP数据源连接池,并使用JdbcTemplate进行数据库操作。通过具体实例展示了配置文件的内容及保存、查询方法的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="123456"/>
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>

<bean id="jdbcStudentDao" class="JdbcStudentDao" >
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
</beans>
以上是我的applicationContext.xml文件:
(1)我使用的是DBCP项目提供的一个数据源连接池,使用DBCP项目配置数据源必须要下载两个JAR包(commons-dbcp-1.4.和commons-pool-1.4.jar),我使用的是1.4版本,这是目前最高的一个版本。
(2)我使用的是mysql数据库。
(3)我使用的是JdbcTemplate,这是Spring里最基本的JDBC模板,只需要设置DataSource就可以让JdbcTemplate工作。
(4)JdbcStudentDao是我自己定义的一个类,
public class JdbcStudentDao{
private JdbcTemplate jdbcTemplate;

public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
现在就可以把JdbcTemplate装配到这个DAO类里了,我们就可以使用jdbcTemplate这个对象来访问数据库了
(5)下面是利用JdbcTemplate进行的保存和查询
public void save() {
String sql = "insert into studentinfo (StudentID,StudentName,Birth,Sex) " +"values (?,?,?,?)";
jdbcTemplate.update(sql,new Object[]{10,"zz","2008-6-24","f"});
}

public List select(StudentInfo studentInfo) {
String sql = "select tudentID,StudentName,Birth,Sex from studentinfo " + "where StudentID=?";
List result=jdbcTemplate.query(sql,
new Object[]{new Long(studentInfo.getStudentID())},
new RowMapper() {
public Object mapRow(ResultSet rs,int rowNum) throws SQLException,DataAccessException {
StudentInfo studentInfo = new StudentInfo();
studentInfo.setStudentID(rs.getLong(1)); studentInfo.setStudentName(rs.getString(2));
studentInfo.setBirth(rs.getString(3));
studentInfo.setSex(rs.getString(4));
return studentInfo; }
});
return result;
}
(6)Spring提供了3个模板,除了上面介绍的JdbcTemplate,还有NamedParameterJdbcTemplate和SimpleJdbcTemplate
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值