The T_persons table is a table that represents "people".
The T_dogs table is a table that represents "dog", and in the T_dogs table there is a foreign key MasterID the primary key ID of the T_persons table.
Package com.rk.db.f_auto_increment;import java.sql.connection;import java.sql.preparedstatement ;import java.sql.resultset;import java.sql.sqlexception;import java.sql.statement;import Com.rk.db.utils.jdbcutil;public class demo01{public static void main (String[] args) {connection conn = null; preparedstatement pstmt1 = null; preparedstatement pstmt2 = null; resultset rs = null;try{string sql1 = "Insert into t_persons (UserName, PWD) values (?,?) "; string sql2 = "Insert into t_dogs (Dname,masterid) values (?,?)"; /Get Connection conn = jdbcutil.getconnection ();// 1, need to specify return self-growth marker pstmt1 = conn.preparestatement ( Sql1,statement.return_generated_keys);p stmt1.setstring (1, "Little Red");p stmt1.setstring (2, "password"); Pstmt1.executeupdate ();// 2, gets the returned self-growing field int masterid = -1;rs = psTmt1.getgeneratedkeys (); if (Rs.next ()) {masterid = rs.getint (1);} 3, using the returned self-growth field pstmt2 = conn.preparestatement (SQL2);p stmt2.setstring (1, "Wang Choi"); Pstmt2.setint (2, masterid);p stmt2.executeupdate ();} catch (sqlexception e) {e.printstacktrace ();} finally{jdbcutil.closequietly (PSTMT1); jdbcutil.closequietly (PSTMT2); jdbcutil.closequietly (conn);}}}
JDBC Series: (6) using PreparedStatement to get self-growth values