基於Spring框架訪問數據庫,需要配置對數據源的引用,建立對數據庫訪問的連接。
1、Spring+jdbc與DataSource的整合應用(基於jdbc的數據源配置注入)
例題:利用Spring框架,並基於JDBC數據源注入方式,實現在數據庫表中插入和查詢數據。
(1)dataSource.xml
<?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.xsd">
<!-- 配置DataSource數據源 -->
<bean id="dataSources"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/spring?serverTimezone=GMT%2B8"></property>
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"></property>
</bean>
<!-- 配置工具類的Bean -->
<bean id="dbUtils" class="com.spring.datasource.DbUtil">
<property name="dataSource" ref="dataSources"></property> <!-- 引用所配置的數據源 -->
</bean>
<!-- 配置DAO的Bean -->
<bean id="userDao" class="com.spring.datasource.UserDAO">
<property name="dbUtil" ref="dbUtils"></property> <!-- 引用所配置的工具Bean -->
</bean>
</beans>
(2) DbUtil工具類
package com.spring.datasource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
public class DbUtil {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
// 從數據源對象dataSource獲取數據連接對象的方法
public Connection getConnection() throws SQLException {
Connection conn = null;
conn = dataSource.getConnection();
return conn;
}
public void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
if (rs != null)
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (pstmt != null)
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}