Spring JDBC更新数据
以下示例将展示如何使用Spring jdbc执行更新数据库表的记录,这里演示如何更新student表中指定条件的记录。
语法:
String updateQuery = "update Student set age = ? where id = ?";
jdbcTemplateObject.update(updateQuery, age, id);
在上面语法中 -
- updateQuery- 具有占位符的更新查询用来更新学生信息。
- jdbcTemplateObject-- StudentJDBCTemplate对象将- Student对象更新到数据库表中。
创建项目
要了解上面提到的Spring JDBC相关的概念,这里创建一个项目用来演示如何更新Student表中的数据记录。打开Eclipse IDE,并按照以下步骤创建一个名称为:UpdateQuery 的Spring应用程序项目。
步骤说明
- 参考第一个Spring JDBC项目来创建一个Maven项目 - http://www.yiibai.com/springjdbc/first_application.html
- 更新bean配置并运行应用程序。
完整的项目结构如下所示 -

文件 : pom.xml 的内容 -
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai</groupId>
    <artifactId>ReadQuery</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
    </dependencies>
</project>
以下是数据访问对象接口文件:StudentDAO.java的代码内容:
package com.yiibai;
import java.util.List;
import javax.sql.DataSource;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
    /**
     * This is the method to be used to initialize database resources ie.
     * connection.
     */
    public void setDataSource(DataSource ds);
    /**
     * This is the method to be used to update a record into the Student table.
     */
    public void update(Integer id, Integer age);
    /**
     * This is the method to be used to list down a record from the Student
     * table corresponding to a passed student id.
     */
    public Student getStudent(Integer id);
}
以下是文件:Student.java的代码内容:
package com.yiibai;
public class Student {
    private Integer age;
    private String name;
    private Integer id;
    public void setAge(Integer age) {
        this.age = age;
    }
    public Integer getAge() {
        return age;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getId() {
        return id;
    }
}
以下是文件:StudentMapper.java的代码内容:
package com.yiibai;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<Student> {
    public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
        Student student = new Student();
        student.setId(rs.getInt("id"));
        student.setName(rs.getString("name"));
        student.setAge(rs.getInt("age"));
        return student;
    }
}
以下是实现类文件:StudentJDBCTemplate.java,它实现了接口StudentDAO.java:
以下是文件:StudentJDBCTemplate.java的代码内容:
package com.yiibai;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentJDBCTemplate implements StudentDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }
    public void update(Integer id, Integer age) {
        String SQL = "update Student set age = ? where id = ?";
        jdbcTemplateObject.update(SQL, age, id);
        System.out.println("Updated Record with ID = " + id);
        return;
    }
    public Student getStudent(Integer id) {
        String SQL = "select * from Student where id = ?";
        Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, new StudentMapper());
        return student;
    }
}
以下是程序执行入口文件:MainApp.java的代码内容:
package com.yiibai;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiibai.StudentJDBCTemplate;
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application-beans.xml");
        StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");
        System.out.println("----Updating Record with ID = 2 -----");
        studentJDBCTemplate.update(2, 19);
        System.out.println("----Listing Record with ID = 2 -----");
        Student student = studentJDBCTemplate.getStudent(2);
        System.out.print("ID : " + student.getId());
        System.out.print(", Name : " + student.getName());
        System.out.println(", Age : " + student.getAge());
    }
}
以下是Bean和数据库配置文件:application-beans.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-3.0.xsd ">
    <!-- Initialization for data source -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>
    <!-- Definition for studentJDBCTemplate bean -->
    <bean id="studentJDBCTemplate" class="com.yiibai.StudentJDBCTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>
注意: application-beans.xml 文件的位置是:{workspace}/fistapp/src/main/java 目录,如果放置错了,程序可能会因为找不到此配置文件而出错。
完成创建源代码和bean和数据库连接信息的文件配置后,运行应用程序。这里先简单说明一下运行的步骤,在项目名称(UpdateQuery)上点击右键,在弹出的菜单中选择:【Run As】-> 【Maven test】
在运行测试成功后,应该会输出类似以下内容(含有 BUILD SUCCESS 的信息) 。
接下来,点击类文件:MainApp.java 选择【Run As】->【Java Application】,如果应用程序一切正常,这将打印以下消息:
----Updating Record with ID = 2 -----
Updated Record with ID = 2
----Listing Record with ID = 2 -----
ID : 2, Name : Minsu, Age : 19
Spring JDBC更新数据的更多相关文章
- Spring JDBC删除数据
		以下示例将展示如何使用Spring jdbc执行删除数据库表中的记录,这里演示如何删除指定student表中的记录. 语法: String deleteQuery = "delete fro ... 
- Spring JDBC查询数据
		以下示例将展示如何使用Spring jdbc进行查询数据记录,将从student表中查询记录. 语法: String selectQuery = "select * from student ... 
- Spring JDBC插入数据
		以下示例将展示如何使用Spring jdbc进行插入查询.将向student表中插入几条记录. 语法: String insertQuery = "insert into student ( ... 
- JDBC更新数据实例
		在本教程将演示如何在JDBC应用程序中,更新数据库的一个表中数据记录. 在执行以下示例之前,请确保您已经准备好以下操作: 具有数据库管理员权限,以在给定模式的数据库表中更新数据记录. 要执行以下示例, ... 
- Spring JDBC处理CLOB类型字段
		以下示例将演示使用spring jdbc更新CLOB类型的字段值,即更新student表中的可用记录. student表的结构如下 - CREATE TABLE student( ID INT NOT ... 
- Spring JDBC处理BLOB类型字段
		以下示例将演示使用spring jdbc更新BLOB类型的字段值,即更新student表中的可用记录. student表的结构如下 - CREATE TABLE student( ID INT NOT ... 
- spring jdbc 批处理插入主健重复的数据
		1.有事务:当调用spring jdbc 的批处理的时候,在实现层加入事物,只要有插入异常的数据,整个批处理操作都会回滚.事务保证操作的原子性. 2.无事务:当没有事务的时候,批处理插入数据的时候,若 ... 
- 【转】在Spring中基于JDBC进行数据访问时怎么控制超时
		http://www.myexception.cn/database/1651797.html 在Spring中基于JDBC进行数据访问时如何控制超时 超时分类 超时根据作用域可做如下层级划分: Tr ... 
- Spring04-SpringEL&Spring JDBC数据访问
		一. SpringEL入门 Spring动态语言(简称SpEL) 是一个支持运行时查询和操作对象图的强大的动态语言,语法类似于EL表达式,具有诸如显示方法和基本字符串模板函数等特性. 1. 准备工作 ... 
随机推荐
- [AWS vs Azure] 云计算里AWS和Azure的探究(1)
			转自:http://www.cnblogs.com/hotcan/archive/2013/01/31/2886794.html 云计算里AWS和Azure的探究(1) 全球领先的云的计算平台主要有两 ... 
- Eclipse工程文件夹 红叹号
			问题产生: 重装系统后,换了个新版本的Eclipse,但是,使用以前的工程目录(工程目录重命名了)后,发现,一些工程上显示红叹号,仔细查看里面的代码,也没有错误 问题原因: 经过查看,是工程中,使用的 ... 
- 【设计模式】适配器模式与Reader、InputStream之间的适配
			简述 适配器模式,目的是将A对象通过适配.转换的方式转换成B对象来使用,为什么转换为B对象?因为用户通过依赖B对象来使用. 适配器的实现有两种方式. 继承实现 组合实现 基于Java单继承的机制,组合 ... 
- analytics详解
			数据来源,手机端上传至服务器端的原始数据 1,基本信息(第一次启动) 字段名 字段类型 备注 是否必填 appkey String Y deviceCode String 设备号 与wifima ... 
- Linux screen用法简介
			[admin@VM_0_2_centos ~]$ screen -bash: screen: 未找到命令 [admin@VM_0_2_centos ~]$ sudo su [sudo] passwor ... 
- Emacs文件命令
			[文件]----------------------------------------C-x C-f 读取文件到Emacs C-x r 只读的方式打开一个文件C-x C-q 清除一个窗口的只读属性 ... 
- Highcharts  多个Y轴动态刷新数据
			效果图: js代码: $(function() { $(document).ready(function() { Highcharts.setOptions({ global: { useUTC: f ... 
- 常用Git命令清单(转)
			文/阮一峰 我每天使用 Git ,但是很多命令记不住. 一般来说,日常使用只要记住下图 6 个命令,就可以了.但是熟练使用,恐怕要记住 60-100 个命令. 下面是我整理的常用 Git 命令清单.几 ... 
- Web Server 与 App Server
			Web Server 常见的Web Server有Apache Server与Nginx. Apache Http Server是Apache软件基金会下的一个项目,是一款开源的HTTP服务器软件(它 ... 
- C语言  ·  字符删除
			算法训练 字符删除 时间限制:1.0s 内存限制:512.0MB 问题描述 编写一个程序,先输入一个字符串str(长度不超过20),再输入单独的一个字符ch,然后程序会把字符串str ... 
