JDBC获取表的主键
JDBC获取表的主键
案例,创建订单,并根据订单号向订单明细表插入数据
sql语句:
创建两表
create table orders(
id number(4) primary key,
customer varchar2(20) not null,
orderdate date default sysdate
);
create table orderDetails(
id number(4) primary key,
order_id number(4),
product varchar2(50) not null,
count number(4) not null,
unitprice number(7,2)
);
这里核心是要使得订单的主键id = order_id
public void OrderInsert(){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = DBUtils.getConnection(); //事务开始 conn.setAutoCommit(false); //业务逻辑 //插入订单表,谁,什么时间 //插入订单明细表,上一步生产的订单号 //插入商品明细,商品单价 pstmt = conn.prepareStatement(INSERT_ORDER, new String[]{"id"});//获取主键名称 pstmt.setString(1, "威震天"); pstmt.setTimestamp(2,new java.sql.Timestamp(System.currentTimeMillis())); pstmt.executeUpdate(); //获取ID值 rs= pstmt.getGeneratedKeys(); int orderId =0 ; if(rs.next()){ orderId = rs.getInt(1); } System.out.println("order id:"+orderId); //事物2: pstmt = conn.prepareStatement(INSERT_DETIAL); pstmt.setInt(1, orderId); pstmt.setString(2, "Cube"); pstmt.setInt(3, 10); pstmt.setDouble(4, 5000); pstmt.executeUpdate(); System.out.println("订单明细已插入"); conn.commit(); } catch (Exception e) { try { conn.rollback(); } catch (SQLException sqkex) { // TODO Auto-generated catch block sqkex.printStackTrace(); } e.printStackTrace(); }finally { try { conn.setAutoCommit(true); if(conn !=null) conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }