spring-JdbcTemplate-08

JdbcTemplate操作数据库


JdbcTemplate类是spring的核心类之一,位于spring-jdbc包org.springframework.jdbc.core.JdbcTemplate中。

要使用JdbcTemlate还需spring-tx包,这个包包含了事务管理和异常控制

  • 可直接通过数据源的引用实例化,在服务中使用。
  • 可通过依赖注入的方式在ApplicationContext中产生,并作为javabean的引用,给服务使用。

JdbcTemplate类包含了核心的jdbc工作流程,如应用程序要创建和执行Statement对象,只需提供SQL语句。

JdbcTemplate类主要方法

  • update方法:用于执行新增、修改、删除等语句;
  • execute方法:用于执行任何SQL语句,一般用于执行DDL语句;
  • query方法及queryForXXX方法:用于执行查询相关语句;
  • batchUpdate方法:用于执行批处理相关语句
  • call方法:用于执行存储过程、函数相关语句。

其中:sql参数指定查询条件的语句,requiredType指定返回对象的类型,args指定查询语句的条件参数


示例

通过数据源的引用实例化jdbcTemplate

<!-- 配置jdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource">
        <ref local="dataSource"/>
    </property>
</bean>

创建类AddUser获取jdbcTemplate对象,并使用其中的update方法。

package jdbcTemplate;

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");
        //获取JdbcTemplate
        jtl =(JdbcTemplate)factory.getBean("jdbcTemplate");
        String sql = "insert into tb_user(name,age,sex) values ('小明','23','男')";//SQL语句
        jtl.update(sql);//执行update操作
        System.out.println("添加操作执行成功");
    }
}

posted @ 2020-12-15 18:50  jt_coder  阅读(91)  评论(0)    收藏  举报