Java obtains the ID of the inserted data in the auto-increment primary key table of the database.

Source: Internet
Author: User
This code is used to solve the problem of automatically generated IDs after inserting data to the auto-increment table in JDBC. I searched for documents online for half a day. I used to provide methods in JDK. Click the link to open the references. Thank you for your guidance. Run the Code directly: *** get the auto-incrementing ID * @ paramsql * @ return * p after the auto-incrementing primary key is inserted.

This code is used to solve the problem of automatically generated IDs after inserting data to the auto-increment table in JDBC. I searched for documents online for half a day. I used to provide methods in JDK. Click the link to open the references. Thank you for your guidance. Run the Code directly:/*** get the auto-incrementing ID after the primary key is inserted * @ param SQL * @ return */p

This code is used to solve the problem of automatically generated IDs after inserting data to the auto-increment table in JDBC. I searched for documents online for half a day. I used to provide methods in JDK.

Click the link to open the references. Thank you for your guidance.

Go directly to the Code:

/*** Get the auto-incrementing ID after the primary key is inserted * @ param SQL * @ return */public int insertIntoDB (String SQL) {Connection conn = null; statement state = null; ResultSet rs = null; int key =-1; try {conn = DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/jx3", "root", "root"); state = conn.createstatement(;;state.exe cuteUpdate (SQL, Statement. RETURN_GENERATED_KEYS); rs = state. getGeneratedKeys (); if (rs. next () {key = rs. getInt (1);} return key;} catch (SQLException e) {e. printStackTrace (); return key;} finally {try {if (rs! = Null) {rs. close (); rs = null;} if (state! = Null) {state. close (); state = null;} if (conn! = Null) {conn. close (); conn = null ;}} catch (SQLException e) {e. printStackTrace ();}}}

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.