Get the database auto-generated primary key value

Source: Internet
Author: User

Package COM.ATGUIGU.JDBC;

Import java.sql.Connection;
Import Java.sql.Date;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import Java.sql.ResultSetMetaData;
Import java.sql.Statement;

Import Org.junit.Test;

public class Jdbctest {
/**
* Get the database auto-generated primary key value
*/
@Test
public void Testgetkeyvalue () {
Connection Connection=null;
PreparedStatement Preparedstatement=null;
try{
Connection=jdbctools.getconnection ();
String sql= "INSERT into Customers (Name,email,birth) VALUES (?,?,?)";

Preparedstatement=connection.preparestatement (SQL,);
Use overloaded preparestatement (Sql,flag) to generate PreparedStatement objects
Preparedstatement=connection.preparestatement (SQL, Statement.return_generated_keys);

Preparedstatement.setstring (1, "Chai Yuxia");
Preparedstatement.setstring (2, "[email protected]");
Preparedstatement.setdate (3, New Date (New Java.util.Date (). GetTime ()));
Preparedstatement.executeupdate ();
Get the Resutlset object that contains the new primary key by using. Getgeneratedkeys ()

There is only one column of Generated_dey in resultset to hold the newly generated primary key value
ResultSet Rs=preparedstatement.getgeneratedkeys ();
if (Rs.next ()) {
System.out.println (Rs.getobject (1));
}
ResultSetMetaData Resultsetmetadata=rs.getmetadata ();
for (int i=0;i<resultsetmetadata.getcolumncount (); i++) {
System.out.println (Resultsetmetadata.getcolumnname (i+1));
}
}catch (Exception e) {
E.printstacktrace ();
}finally{
Jdbctools.release (NULL, PreparedStatement, connection);
}
}

}

Get the database auto-generated primary key value

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.