Spring 中 JDBC 的相关信息是在 Spring 配置文件中完成的,其配置模板如下所示:
① mysql数据库版本为8.0
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
">
<!-- 配置数据源 ,建议下面class后面的路径自行复制自己的(避免包名大小写问题)-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--数据库驱动 -->
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<!--连接数据库的url -->
<property name="url" value="jdbc:mysql://localhost:3306/数据库名字?serverTimezone=UTC"></property>
<!--连接数据库的用户名 -->
<property name="username" value="root"></property>
<!--连接数据库的密码 -->
<property name="password" value="123456"></property>
</bean>
<!--配置JDBC模板 -->
<!-- 配置jdbcTemplate,数据库操作工具类,使用它完成CRUD -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置注入类 -->
<bean id="xxx" class="xxx">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
</beans>
② mysql数据库版本为5.0
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
">
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--数据库驱动 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<!--连接数据库的url -->
<property name="url" value="jdbc:mysql://localhost:3306/数据库名字"></property>
<!--连接数据库的用户名 -->
<property name="username" value="root"></property>
<!--连接数据库的密码 -->
<property name="password" value="123456"></property>
</bean>
<!--配置JDBC模板 -->
<!-- 配置jdbcTemplate,数据库操作工具类,使用它完成CRUD -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置注入类 -->
<bean id="xxx" class="xxx">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
</beans>