- spring 提供用于操作JDBC工具类,类似:DBUtils。
- 依赖 连接池DataSource (数据源)。
一、环境搭建
1.1 创建表
create database ee19_spring_day02;
use ee19_spring_day02;
create table t_user(
id int primary key auto_increment,
username varchar(50),
password varchar(32)
);
insert into t_user(username,password) values('jack','1234');
insert into t_user(username,password) values('rose','5678');
1.2 导入jar包
1.3 javabean
public class User {
private Integer id;
private String username;
private String password;
二、使用api(了解)
public static void main(String[] args) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/ee19_spring_day02");
dataSource.setUsername("root");
dataSource.setPassword("1234");
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
jdbcTemplate.update("insert into t_user(username,password) values(?,?);", "tom","998");
}
三、配置DBCP
<bean id="dataSourceId" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ee19_spring_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
<bean id="jdbcTemplateId" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSourceId"></property>
</bean>
<bean id="userDaoId" class="com.itheima.c_dbcp.UserDao">
<property name="jdbcTemplate" ref="jdbcTemplateId"></property>
</bean>
四、配置C3P0
<bean id="dataSourceId" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ee19_spring_day02"></property>
<property name="user" value="root"></property>
<property name=
五、使用JdbcDaoSupport
5.1 dao层
5.2 spring配置文件
<bean id="userDaoId" class="com.itheima.e_jdbcdaosupport.UserDao">
<property name="dataSource" ref="dataSourceId"></property>
</bean>
5.3 源码分析
六、配置properties
6.1 properties文件
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ee19_spring_day02
jdbc.user=root
jdbc.password=1234
6.2 spring配置
<context:property-placeholder location="classpath:com/itheima/f_properties/jdbcInfo.properties"/>
<bean id="dataSourceId" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>