Use of Prepared Statement and getting Foriegn Key from Master Table

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class PreparedTest {

    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://127.1.1.1:3306/sample","root","matix");
            StringBuilder query1 = new StringBuilder();
            query1.append("insert into user_master (userid, loginid, password) values (0,'taher','taher')");
            PreparedStatement pst = con.prepareStatement(query1.toString());
            pst.executeUpdate();

            ResultSet keys = pst.getGeneratedKeys();
            keys.next();
            int key = keys.getInt(1);
            System.out.println("Keys : "+key);
            pst.close();

            StringBuilder query2 = new StringBuilder();
            query2.append("insert into user_detail(user_detailid, userid, usertypeid, fname, lname, address, sex, countryid, stateid, city, datentime) ");
            query2.append( "values(0,"+key+",1,'tt','tt','tt','m',1,1,'ahmed',current_timestamp)");
            PreparedStatement pst2 = con.prepareStatement(query2.toString());
            pst2.executeUpdate();
            pst2.close();

            con.close();

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}
Advertisements
This entry was posted in JDBC, JSP. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s