JDBC Gets the primary key of the table

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.