JDBC Series: (6) using PreparedStatement to get self-growth values

Source: Internet
Author: User


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

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.