JDBC Gets the primary key of the table
Case, create an order, and insert data into the order list according to the order number
SQL statements:
Create two tables
CREATE TABLE Orders (
ID Number (4) primary key,
Customer VARCHAR2 () not NULL,
OrderDate Date Default Sysdate
);
CREATE TABLE OrderDetails (
ID Number (4) primary key,
ORDER_ID Number (4),
Product VARCHAR2 (not NULL),
Count Number (4) is not NULL,
UnitPrice Number (7,2)
);
The core here is to make the order's primary Key ID = order_id
Public voidOrderInsert () {Connection conn=NULL; PreparedStatement pstmt=NULL; ResultSet RS=NULL; Try{conn=dbutils.getconnection (); //Transaction StartConn.setautocommit (false); //Business Logic//Insert Order form, who, what time//Insert Order form, previous step production order number//Insert Product details, product pricePSTMT =conn.preparestatement (Insert_order,Newstring[]{"id"});//get primary Key namepstmt.setstring (1, "Megatron."); Pstmt.settimestamp (2,NewJava.sql.Timestamp (System.currenttimemillis ())); Pstmt.executeupdate (); //Get ID valuers=Pstmt.getgeneratedkeys (); intOrderId =0 ; if(Rs.next ()) {orderId= Rs.getint (1); } System.out.println ("Order ID:" +orderId); //Thing 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 ("Order details are inserted"); Conn.commit (); } Catch(Exception e) {Try{conn.rollback (); } Catch(SQLException Sqkex) {//TODO auto-generated Catch blockSqkex.printstacktrace (); } e.printstacktrace (); }finally { Try{conn.setautocommit (true); if(Conn! =NULL) Conn.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }
JDBC Gets the primary key of the table