JDBC获取表的主键
时间:2021-07-01 10:21:17
帮助过:3人阅读
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();
}
}
}
JDBC获取表的主键
标签: