Java开发基础-JDBC-核心对象的使用—06

PreparedStatement另一种重载方法:

下面是JavaAPI在中对其的描述

Connection.prepareStatement(String sql, String[] columnNames)  String[] columnNames 表示的是自动生成值的列名

创建一个能够返回由给定数组指定的自动生成键的默认 PreparedStatement 对象。

可以从中取出新插入数据行中自动增长的列的值

下面通过简单实例演示如何使用

1.创建测试所需的数据库表以及序列 

create table depts_cheri (
  deptno number(8)  primary key,
  dname varchar(20),
  loc varchar(100)
);

create sequence depts_seq_cheri;

create table emp_cheri (
  empno   number(8) primary key,
  ename   varchar(20),
  job     varchar(20),
  mgr     number(8),
  hiredate  date,
  sal     number(11,2),
  comm    number(11,2),
  deptno    number(8)
);

create sequence emps_seq;

2.编写测试程序

public class TestDay03 {
	
	/**
	 * 添加部门,然后向此部门内添加一些员工
	 */
	@Test
	public void test4(){
		//假设要添加的部门数据如下
		String dname = "财务部";
		String loc = "北京";
		
		//假设要添加的员工数据如下
		String ename = "张三";
		String job = "经理";
		int mgr = 0;
		double sal = 8000.0;
		double comm = 2000.0;
		
		String ename2 ="李四";
		String job2 = "职员";
		int mgr2 = 0;
		double sal2 = 5000.0;
		double comm2 = 500.0;
		
		Connection conn = null;
		
		try {
			conn = DBUtil.getConnection();
			conn.setAutoCommit(false);
			
			//先添加部门
			String sql ="insert into depts_cheri values("
					    +"depts_seq_cheri.nextval,?,?)";
			System.out.println(sql);
			//参数2是一个数组,存的是希望被ps记住的字段的名称
			PreparedStatement ps = conn.prepareStatement(sql,new String[]{"deptno"});
			ps.setString(1, dname);
			ps.setString(2, loc);
			ps.executeUpdate();
			
			//从ps中获取它之前记录的字段的值,
			//返回的结果集中只有一条数据。
			//存的就是记录的那些字段的值
			ResultSet rs = ps.getGeneratedKeys();
			rs.next();
			int deptno = rs.getInt(1);//对应ps记录的参数2中数组的元素顺序
			
			//再添加员工
		   sql = "insert into emp_cheri values("
				 +"emps_seq.nextval,?,?,?,?,?,?,?)";
		   //员工1
		   ps = conn.prepareStatement(sql);
		   ps.setString(1, ename);
		   ps.setString(2, job);
		   ps.setInt(3, mgr);
		   ps.setDate(4, null);
		   ps.setDouble(5, sal);
		   ps.setDouble(6, comm);
		   ps.setInt(7, deptno);
		   ps.executeUpdate();
		   
		   //员工2
		   ps = conn.prepareStatement(sql);
		   ps.setString(1, ename2);
		   ps.setString(2, job2);
		   ps.setInt(3,mgr2);
		   ps.setDate(4, null);
		   ps.setDouble(5, sal2);
		   ps.setDouble(6, comm2);
		   ps.setInt(7, deptno);
		   ps.executeUpdate();
		   
			conn.commit();
			
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
			throw new RuntimeException("添加部门与员工失败!",e);
		}finally{
			DBUtil.close(conn);
		}
		
	}

}

使用Junit方式运行程序后,查看数据库中数据的变化,可以发现数据已成功保存!


适用场合:

当插入数据库中的某一字段column与某一自动增长的列相同时,使用该重载方法取出自动增长的列的字段值,然后将该自动增长列赋值给column字段。

猜你喜欢

转载自blog.csdn.net/coder_boy_/article/details/80643697