when inserting data into a table, if the primary key is a self-growing type, then we can not assign a value to the primary key column, but sometimes the primary key is exactly the foreign key of the other table, then we need to know the value of the self-growth, of course, we can execute a query statement, according to the information you inserted when the condition, The easy way to do this is to return the primary key directly after inserting the SQL statement.
Packagejdbc_preparement;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.sql.Blob;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;ImportJava.sql.ResultSetMetaData;Importjava.sql.SQLException;Importjava.sql.Statement; Public classtext_preparestartment { Public Static voidMain (string[] args) {//TODO auto-generated Method StubConnection con=simplecon.getconnection (); Create a JDBC connection with a packaged custom class String SQL= "INSERT into t_user values (null,?,?, null);";Try{PreparedStatement PS=con.preparestatement (Sql,statement.return_generated_keys);//A parameter that indicates the need to return the primary key ps.setstring (1, "Mike"); Ps.setstring (2, "4399"); Ps.execute (); ResultSet Re=Ps.getgeneratedkeys (); Returns the primary key Re.next (); intN=re.getint (1); System.out.println ("The natural growth of the serial number is" +N); Output primary key simplecon.close (re); Simplecon.close (PS);simplecon.close (con); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}classsimplecon{StaticConnection con; StaticConnection getconnection () {Try{con=drivermanager.getconnection ("Jdbc:mysql://localhost:3306/test", "Database user name", "Database Password"); }Catch(SQLException e) {e.printstacktrace (); } returncon; } Static voidClose (autocloseable a) {Try{a.close (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
JDBC obtains the Auto_increment class primary key in the database table