需要环境
所需jar包
连接dbcp连接池
方法一:不使用jdbc.properties
1.配置dacp连接池
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="liuqing.1998" />
</bean>
2.创建dataSources属性
private DataSource dataSource;
3.创建set get方法。set方法上@Resource获取xml中id="dataSource"
的bean。
public DataSource getDataSource() {
return dataSource;
}
@Resource
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
4.获取数据库连接
dataSource提供一个getConnection()方法获取连接。
@Override
public void save(User user) {
try {
Connection conn = dataSource.getConnection();
conn.createStatement().executeUpdate("insert into user values(null,'213')");
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("user add to mysql...");
}
方法二:使用jdbc.properties
1.src路径下创建jdbc.properties文件
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
jdbc.username=root
jdbc.password=liuqing.1998
2.配置dbcp连接池
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<context:property-placeholder location="jdbc.properties"/>