Jdbc Template 类是 Spring 的核心类之一,简化了编写 JDBC 时所需的基础代码
例:利用Jdbc Template 在数据表中添加用户信息
1、在 applicationContext.xml 文件中新增配置代码:
<!-- 配置jdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref local="dataSource"/>
</property>
</bean>
2、创建类addUser,获取 Jdbc Template 对象,并利用其 update()方法执行数据库的添加操作
代码如下:
package com.mr.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class addUser {
// 利用JdbcTemplate添加数据
public static void main(String[] args) {
JdbcTemplate jtl = null;
ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");// 获取配置文件
jtl = (JdbcTemplate) factory.getBean("jdbcTemplate");// 获取JdbcTemplate
String sql = "insert into huiyuan(name,age,sex) values ('小明','23','男')";// SQL语句
jtl.update(sql);// 执行添加操作
System.out.println("添加操作执行成功");// 输出信息
}
}
运行结果: