Spring JdbcTemplate 的常用方法之execute update query方法

在JdbcTemplate核心类中,提供了大量的更新和查询数据库的方法,我们就是使用的这些方法来操作数据库的。
常用方法如下图所示:
在这里插入图片描述
使用jdbc运行数据库语句,使用之前先导入包,Spring包以及jdbc驱动包

execute update query 方法

创建一个表:首先在数据库当中要明确在哪一个库下面创建,以及表的行列。
比如创建一个三列数据的表格:先对变量进行定义以及封装。

package com.jdbc;
public class Account {	
	private Integer id;       // 账户id
	private String username; // 用户名
	private Double balance;  // 账户余额	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public Double getBalance() {
		return balance;
	}
	public void setBalance(Double balance) {
		this.balance = balance;
	}
}

随后,定义一个接口,对表数据进行增删改的操作

package com.jdbc;
import java.util.List;
public interface AccountDao {	
	// 添加
	public int addAccount(Account account);
	// 更新
	public int updateAccount(Account account);
	// 删除
	public int deleteAccount(int id);
	// 通过id查询
	public Account findAccountById(int id);
	// 查询所有账户
	public List<Account> findAllAccount();
}

在类中实现接口当中的方法。增删改查的方法的具体实现,这里也就不做详细的解释了。

package com.jdbc;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class AccountDaoImpl implements AccountDao {
	// 声明JdbcTemplate属性及其setter方法
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
    // 添加账户
	public int addAccount(Account account) {
		// 定义SQL
		String sql = "insert into account(username,balance) value(?,?)";
		// 定义数组来存放SQL语句中的参数
		Object[] obj = new Object[] { 
                           account.getUsername(), 
                           account.getBalance() 
         };
		// 执行添加操作,返回的是受SQL语句影响的记录条数
		int num = this.jdbcTemplate.update(sql, obj);
		return num;
	}
	// 更新账户
	public int updateAccount(Account account) {
		// 定义SQL
		String sql = "update account set username=?,balance=? where id = ?";
		// 定义数组来存放SQL语句中的参数
		Object[] params = new Object[] { 
                               account.getUsername(), 
                               account.getBalance(), 
                               account.getId() 
          };
		// 执行添加操作,返回的是受SQL语句影响的记录条数
		int num = this.jdbcTemplate.update(sql, params);
		return num;
	}
	// 删除账户
	public int deleteAccount(int id) {
		// 定义SQL
		String sql = "delete  from account where id = ? ";
		// 执行添加操作,返回的是受SQL语句影响的记录条数
		int num = this.jdbcTemplate.update(sql, id);
		return num;
	}
	
	// 通过id查询账户数据信息
	public Account findAccountById(int id) {
	    //定义SQL语句
	    String sql = "select * from account where id = ?";
	    // 创建一个新的BeanPropertyRowMapper对象
	    RowMapper<Account> rowMapper = 
	new BeanPropertyRowMapper<Account>(Account.class);
	    // 将id绑定到SQL语句中,并通过RowMapper返回一个Object类型的单行记录
	    return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
	}	
	// 查询所有账户信息
	public List<Account> findAllAccount() {
	    // 定义SQL语句
	    String sql = "select * from account";
	    // 创建一个新的BeanPropertyRowMapper对象
	    RowMapper<Account> rowMapper = 
	new BeanPropertyRowMapper<Account>(Account.class);
	    // 执行静态的SQL查询,并通过RowMapper返回结果
	    return this.jdbcTemplate.query(sql, rowMapper);
	}
}

再就是配置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-4.3.xsd">
	<!-- 1配置数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!--数据库驱动 -->
		<property name="driverClassName"
			value="com.mysql.jdbc.Driver" />
		<!--连接数据库的url,应为这里是下载的最新版的jdbc驱动包有时区问题,不同的话把?后面的删除掉即可 -->
		<property name="url"
			value="jdbc:mysql://localhost:3306/spring?serverTimezone=UTC" />
		<!--连接数据库的用户名 -->
		<property name="username" value="root" />
		<!--连接数据库的密码 -->
		<property name="password" value="root" />
	</bean>
	<!-- 2配置JDBC模板 -->
	<bean id="jdbcTemplate"
		class="org.springframework.jdbc.core.JdbcTemplate">
		<!-- 默认必须使用数据源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!--定义id为accountDao的Bean -->
	<bean id="accountDao" class="com.jdbc.AccountDaoImpl">
		<!-- 将jdbcTemplate注入到accountDao实例中 -->
		<property name="jdbcTemplate" ref="jdbcTemplate" />
	</bean>
</beans>

定义一个测试类:在main函数当中执行创建表语句

package com.jdbc;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTemplateTest {
	//使用execute()方法建表
	public static void main(String[] args) {
		// 加载配置文件
		ApplicationContext ac = 
		   new ClassPathXmlApplicationContext("applicationContext.xml");
		// 获取JdbcTemplate实例,获取bean对象
		JdbcTemplate jdTemplate = 
			   (JdbcTemplate) ac.getBean("jdbcTemplate");
		// 使用execute()方法执行SQL语句,创建用户账户管理表account
		jdTemplate.execute("create table account(" + 
					         "id int primary key auto_increment," +
					         "username varchar(50)," + 
					         "balance double)");
		System.out.println("账户表account创建成功!");
	}
}

再者就是执行插入语句:同理先加载ApplicationContext ,然后获取bean对象,在获取Account对象并且给其变量设置值,

AccountDao accountDao = 
	            (AccountDao) ac.getBean("accountDao");
	    // 创建Account对象,并向Account对象中添加数据
	    Account account = new Account();
	    account.setUsername("tom");
	    account.setBalance(1000.00);
	    // 执行addAccount()方法,并获取返回结果
	    int num = accountDao.addAccount(account);
	    if (num > 0) {
	        System.out.println("成功插入了" + num + "条数据!");
	    } else {
	        System.out.println("插入操作执行失败!");
	    }

再就是修改表语句:同上,

 AccountDao accountDao = 
	            (AccountDao) applicationContext.getBean("accountDao");
	    // 创建Account对象,并向Account对象中添加数据
	    Account account = new Account();
	    account.setId(1);
	    account.setUsername("tom");
	    account.setBalance(2000.00);
	    // 执行updateAccount()方法,并获取返回结果
	    int num = accountDao.updateAccount(account);
	    if (num > 0) {
	        System.out.println("成功修改了" + num + "条数据!");
	    } else {
	        System.out.println("修改操作执行失败!");
	    }

再就是删除语句,删除语句传入一个参数就是id的值,根据id的值进行删除

AccountDao accountDao = 
	            (AccountDao) applicationContext.getBean("accountDao");
	    // 执行deleteAccount()方法,并获取返回结果
	    int num = accountDao.deleteAccount(1);
	    if (num > 0) {
	        System.out.println("成功删除了" + num + "条数据!");
	    } else {
	        System.out.println("删除操作执行失败!");
	    }

查询所有信息,根据id查询出所有信息。

AccountDao accountDao = 
	            (AccountDao) ac.getBean("accountDao");
	    Account account = accountDao.findAccountById(1);
	    System.out.println(account);

再者就是查询表中所有信息,并进行循环遍历输出

List<Account> account = accountDao.findAllAccount();
	    // 循环输出集合中的对象
	    for (Account act : account) {
	        System.out.println(act);
	    }
发布了295 篇原创文章 · 获赞 42 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_44973159/article/details/104976936