MySQL obtains the value of the auto_increment field just inserted.

Source: Internet
Author: User

MySQL obtains the value of the auto_increment field just inserted.

Select max (ID) from testnotnull cannot be used;

In this way, you can obtain the value of the incremental field you just inserted,

Multithreading is not considered.

 

A better method is:

Use Java. SQL. preparedstatement pstmt = conn. preparestatement (SQL, statement. return_generated_keys );

After inserting data, that is, after executing pstmt.exe cuteupdate,

Resultset rs = pstmt. getgeneratedkeys (); obtain the value of the newly inserted auto-increment field.

Test code:

 

@ Test <br/> Public void testnextvalue () {<br/> try {<br/> string MySQL = "JDBC: mysql: // localhost/hibernate "; <br/> class. forname ("com. mySQL. JDBC. driver "); <br/> JAVA. SQL. connection conn = drivermanager. getconnection (MySQL, "root", "root"); <br/> string SQL = "insert into testnotnull values (null ,?, ?) "; <Br/> JAVA. SQL. preparedstatement pstmt = Conn. preparestatement (SQL, statement. return_generated_keys); <br/> Conn. setautocommit (false); <br/> int I = 1; <br/> pstmt. setint (I ++, 234); <br/> pstmt. setstring (I ++, "sdfsdf"); <br/> pstmt.exe cuteupdate (); <br/> resultset rs = pstmt. getgeneratedkeys (); <br/> system. out. println ("the value is"); <br/> If (RS. next () {<br/> system. out. println (RS. getint (1); <br/>}< br/> Conn. commit (); <br/> Conn. setautocommit (true); <br/>} catch (exception e) {<br/> E. printstacktrace (); <br/>}finally {<br/> // do close .... <br/>}< br/>}

If you only want to obtain the maximum value of auto_increment

Select max (ID) from testnotnull;

Or show table status from Hibernate like 'testnotnull '; To Get The auto_increment value.

Neither of these methods is thread-Safe !!!!!

 

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.