Spring使用数据库连接池操作数据库(简单实现)

1 导入相关jar包

2 在xml文件中写好配置 (tx context aop )还有相关网页

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">

3创建连接池
<!--数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
</bean>
 
4连接JDBC
<!--连接JDBC-->
<bean class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>

<context:component-scan base-package="com.qq"/>
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
5新建一个类
public class AccountService {

@Autowired
DataSource dataSource;
@Autowired
JdbcTemplate jdbcTemplate;
/* @Transactional 事物*/
@Transactional(propagation = Propagation.REQUIRED)
public void transfer() throws Exception{



//Spring有一个轻量级的数据访问框架 jdbcTemplate

int num1= jdbcTemplate.update("update book set price=price-100 where id=1");
int num2= jdbcTemplate.update("update book set price=price+100 where id=2");

}
}
 
 
posted @ 2022-07-29 20:33  java小寇  阅读(169)  评论(0)    收藏  举报