Spring对JDBC的支持访问数据库

基于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();
			}
	}
}
发布了136 篇原创文章 · 获赞 54 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Flora_SM/article/details/103409109