Spring框架|集成JdbcTemplate


关于Spring的JdbcTemplate介绍

完整的XML配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd ">
	<!-- 配置连接池对象 -->
	<bean id="pool" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybase2" />
		<property name="user" value="root"/>
		<property name="password" value="Hudie"/>
	</bean>
	<!-- 配置JdbcTemplate模板对象 -->	
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="pool"></property>
	</bean>
</beans>

(1)编写Spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"

</beans>

(2)配置数据源

在这里插入图片描述
这里使用的连接池是c3p0

	<!-- 配置连接池对象 -->
	<bean id="pool" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybase2" />
		<property name="user" value="root"/>
		<property name="password" value="Hudie"/>
	</bean>

(3)配置JdbcTemplate模板对象

	<!-- 配置JdbcTemplate模板对象 -->	
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="pool"></property>
	</bean>

(4)测试Spring框架集成JdbcTemplate

	@Test
	public void testSpringJdbcTemplate(){
		ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		JdbcTemplate jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");
		String sql ="INSERT INTO user values(NULL,?,?)";
		int result = jdbcTemplate.update(sql, "xx",23);
		System.out.println(result);
	}

打印结果如下,成功先数据库中添加了记录。
在这里插入图片描述
在这里插入图片描述

发布了385 篇原创文章 · 获赞 1033 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/weixin_43691058/article/details/104148659
今日推荐