Spring 对JDBC操作(实现增删改查,批量添加功能)

Spring  对JDBC操作(实现增删改查,批量添加功能)


spring支持对jdbc操作,下面将演示实现增删改查,批量添加功能。本人在数据库中创建了一张部门表,表的结构如下(数据自行填充):


下面是本人的项目:





applicationContext.xml为spring的主配置文件,本人在该配置文件中进行了数据库的修改配置,JDBCTest.java 为本人演示的测试类,Dept.java 为部门实体类。在测试中采用了junit单元测试的方式。 lib目录下为需要的jar包


下面是各个类的代码:


1、JDBCTest.java


package cz.sz.hcq.test;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.support.rowset.SqlRowSet;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import cn.sz.hcq.pojo.Dept;

public class JDBCTest {
	@Test
	// 添加操作
	public void testsave() {
		// 创建数据源---实现数据库的连接
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");// 数据库驱动
		dataSource
				.setUrl("jdbc:mysql://localhost:3306/db?characterEncoding=utf8");// 数据库连接和编码方式
		dataSource.setUsername("root");// 用户名
		dataSource.setPassword("root");// 密码

		// 创建一个部门对象
		Dept dept = new Dept();
		dept.setDname("开发部");
		dept.setLoc("北京");
		// 模板类对象
		JdbcTemplate template = new JdbcTemplate(dataSource);
		// 插入语句
		String sql = "insert into dept(dname,loc) values(?,?)";
		// 执行添加操作
		int result = template.update(sql, dept.getDname(), dept.getLoc());
		System.out.println("result=" + result);
	}

	@Test
	// 修改操作
	public void testupdate() {
		// 创建数据源---实现数据库的连接
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");// 数据库驱动
		dataSource
				.setUrl("jdbc:mysql://localhost:3306/db?characterEncoding=utf8");// 数据库连接和编码方式
		dataSource.setUsername("root");// 用户名
		dataSource.setPassword("root");// 密码

		// 创建一个部门对象
		Dept dept = new Dept();
		dept.setDeptno(104);
		dept.setDname("技术部");
		dept.setLoc("上海");
		// 模板类对象
		JdbcTemplate template = new JdbcTemplate(dataSource);
		// 修改语句
		String sql = "update dept set dname=?,loc=? where deptno=?";
		// 执行修改操作
		int result = template.update(sql, dept.getDname(), dept.getLoc(),
				dept.getDeptno());
		System.out.println("result=" + result);
	}

	@Test
	// 删除操作
	public void testdelete() {
		// 创建数据源---实现数据库的连接
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");// 数据库驱动
		dataSource
				.setUrl("jdbc:mysql://localhost:3306/db?characterEncoding=utf8");// 数据库连接和编码方式
		dataSource.setUsername("root");// 用户名
		dataSource.setPassword("root");// 密码

		// 创建一个部门对象
		Dept dept = new Dept();
		dept.setDeptno(104);
		// 模板类对象
		JdbcTemplate template = new JdbcTemplate(dataSource);

		// 删除语句
		String sql = "delete from dept where deptno=?";
		// 执行删除操作
		int result = template.update(sql, dept.getDeptno());
		System.out.println("result=" + result);
	}

	@Test
	// 批量添加操作操作
	public void testbatchsave() {
		// 创建数据源---实现数据库的连接
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");// 数据库驱动
		dataSource
				.setUrl("jdbc:mysql://localhost:3306/db?characterEncoding=utf8");// 数据库连接和编码方式
		dataSource.setUsername("root");// 用户名
		dataSource.setPassword("root");// 密码

		// 创建多个部门对象
		Dept d1 = new Dept();
		d1.setDname("维护部");
		d1.setLoc("美国");

		Dept d2 = new Dept();
		d2.setDname("销售部");
		d2.setLoc("日本");

		Dept d3 = new Dept();
		d3.setDname("美国部");
		d3.setLoc("英国");

		// 将多个对象添加到list集合中
		final List<Dept> depts = new ArrayList<>();
		depts.add(d1);
		depts.add(d2);
		depts.add(d3);

		// 模板类对象
		JdbcTemplate template = new JdbcTemplate(dataSource);
		// 添加语句
		String sql = "insert into dept(dname,loc) values(?,?)";
		// 执行操作
		template.batchUpdate(sql, new BatchPreparedStatementSetter() {

			@Override
			public void setValues(PreparedStatement pstat, int i)
					throws SQLException {
				Dept dept = depts.get(i);
				pstat.setString(1, dept.getDname());
				pstat.setString(2, dept.getLoc());
			}

			@Override
			public int getBatchSize() {
				// 设置本批次一共多少组数据,隐含的就是循环几次
				return depts.size();
			}
		});
	}

	@Test
	// 根据部门编号查询部门名称操作
	public void testfinddnamebydeptno() {
		// 创建数据源---实现数据库的连接
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");// 数据库驱动
		dataSource
				.setUrl("jdbc:mysql://localhost:3306/db?characterEncoding=utf8");// 数据库连接和编码方式
		dataSource.setUsername("root");// 用户名
		dataSource.setPassword("root");// 密码

		// 创建一个部门对象
		Dept dept = new Dept();
		dept.setDeptno(104);

		// 模板类对象
		JdbcTemplate template = new JdbcTemplate(dataSource);
		// 查询语句
		String sql = "select dname from dept where deptno=?";
		// 执行查询操作
		String dname = template.queryForObject(sql, String.class, 105);
		System.out.println("部门编号为105的部门名称:" + dname);
	}

	@Test
	// 统计共有多少个部门
	public void testcount() {
		// 创建数据源---实现数据库的连接
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");// 数据库驱动
		dataSource
				.setUrl("jdbc:mysql://localhost:3306/db?characterEncoding=utf8");// 数据库连接和编码方式
		dataSource.setUsername("root");// 用户名
		dataSource.setPassword("root");// 密码

		// 模板类对象
		JdbcTemplate template = new JdbcTemplate(dataSource);
		// 查询语句
		String sql = "select count(deptno) from dept";
		// 执行查询操作
		int count = template.queryForObject(sql, int.class);
		System.out.println("部门总数为:" + count);
	}

	@Test
	// 查询部门编号在102-104的部门名称
	public void testquery1() {
		// 创建数据源---实现数据库的连接
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");// 数据库驱动
		dataSource
				.setUrl("jdbc:mysql://localhost:3306/db?characterEncoding=utf8");// 数据库连接和编码方式
		dataSource.setUsername("root");// 用户名
		dataSource.setPassword("root");// 密码

		// 模板类对象
		JdbcTemplate template = new JdbcTemplate(dataSource);
		// 查询语句
		String sql = "select dname from dept where deptno in(?,?,?)";
		// 执行查询操作
		List<String> list = template.queryForList(sql, String.class, 102, 103,
				104);
		for (int i = 0; i < list.size(); i++) {
			String string = list.get(i);
			System.out.println(string);
		}
	}

	@Test
	// 查询部门总数和部门最大编号(返回一个结果集,queryForRowSet查询)
	public void testquery2() {
		// 创建数据源---实现数据库的连接
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");// 数据库驱动
		dataSource
				.setUrl("jdbc:mysql://localhost:3306/db?characterEncoding=utf8");// 数据库连接和编码方式
		dataSource.setUsername("root");// 用户名
		dataSource.setPassword("root");// 密码

		// 模板类对象
		JdbcTemplate template = new JdbcTemplate(dataSource);
		// 查询语句
		String sql = "select count(deptno),max(deptno) from dept";
		// 执行查询操作
		SqlRowSet rs = template.queryForRowSet(sql);
		while (rs.next()) {
			System.out.println("部门总数:" + rs.getInt(1) + ",部门最大编号:"
					+ rs.getInt(2));
		}
	}

	@Test
	// 将查询出来的结果封装为对象
	public void testquery3() {
		// 这里演示使用配置文件来连接数据库(本人在src创建了spring配置文件applicationContext.xml,并在该文件做了配置)
		// 读取配置文件
		ApplicationContext ac = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		// 获取数据源对象
		ComboPooledDataSource dataSource = ac.getBean("dataSource",
				ComboPooledDataSource.class);
		// 模板类对象
		JdbcTemplate template = new JdbcTemplate(dataSource);
		// 查询语句
		String sql = "select * from dept where deptno=?";

		// 将查询出来的数据封装到一个对象中
		Dept dept = template.queryForObject(sql, new MyRowMapper(), 105);

		System.out.println("部门编号:" + dept.getDeptno() + ",部门名称:"
				+ dept.getDname() + ",部门地址:" + dept.getLoc());

	}

	@Test
	// 将查询出来的结果封装为对象(查询为集合形式)
	public void testquery4() {
		// 这里演示使用配置文件来连接数据库(本人在src创建了spring配置文件applicationContext.xml,并在该文件做了配置)
		// 读取配置文件
		ApplicationContext ac = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		// 获取数据源对象
		ComboPooledDataSource dataSource = ac.getBean("dataSource",
				ComboPooledDataSource.class);
		// 模板类对象
		JdbcTemplate template = new JdbcTemplate(dataSource);
		// 查询语句
		String sql = "select * from dept";

		// 将查询出来的数据封装到一个对象中
		List<Dept> list = template.query(sql, new MyRowMapper());
		for (Dept d : list) {
			System.out.println("部门编号:" + d.getDeptno() + ",部门名称:"
					+ d.getDname() + ",部门地址:" + d.getLoc());
		}

	}

	// 将查询结果封装为实体对象
	class MyRowMapper implements RowMapper<Dept> {

		@Override
		public Dept mapRow(ResultSet rs, int arg1) throws SQLException {
			Dept dept = new Dept();
			dept.setDeptno(rs.getInt(1));
			dept.setDname(rs.getString(2));
			dept.setLoc(rs.getString(3));
			return dept;
		}

	}
}





2、applicationContext.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"
	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">

	<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property> 
		<property name="url" value="jdbc:mysql://localhost:3306/db?characterEncoding=utf8"></property> 
		<property name="username" value="root"></property> <property name="password" 
		value="111"></property> </bean> -->

	<!--这里使用c3p0数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl"
			value="jdbc:mysql://localhost:3306/db?characterEncoding=utf8"></property>
		<property name="user" value="root"></property>
		<property name="password" value="root"></property>
		<property name="initialPoolSize" value="10"></property>
		<property name="maxIdleTime" value="30"></property>
		<property name="maxPoolSize" value="100"></property>
		<property name="minPoolSize" value="10"></property>
		<property name="maxStatements" value="200"></property>
	</bean>
</beans>




3、Dept.java

package cn.sz.hcq.pojo;

import java.io.Serializable;

public class Dept implements Serializable {
	private Integer deptno;
	private String dname;
	private String loc;

	public Integer getDeptno() {
		return deptno;
	}

	public void setDeptno(Integer deptno) {
		this.deptno = deptno;
	}

	public String getDname() {
		return dname;
	}

	public void setDname(String dname) {
		this.dname = dname;
	}

	public String getLoc() {
		return loc;
	}

	public void setLoc(String loc) {
		this.loc = loc;
	}

}




  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值