Java Last Insert Id


SQL
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `userpass` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Table structure for address
-- ----------------------------
DROP TABLE IF EXISTS `address`;
CREATE TABLE `address` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `users_id` int(11) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `address_ibfk_1` (`users_id`),
  CONSTRAINT `address_ibfk_1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;


Java Code

import java.sql.*;
public class MainApp {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/db_java", "root", "");
            PreparedStatement stmt = con.prepareStatement("insert into users(username,userpass) values (?,?)", Statement.RETURN_GENERATED_KEYS);
            stmt.setString(1, "Ram");
            stmt.setString(2, "Pukar");
            stmt.execute();
            ResultSet Rs = stmt.getGeneratedKeys();
            if (Rs.next()) {
                ;
                PreparedStatement stmt1 = con.prepareStatement("insert into address(users_id,email,phone) values (?,?,?)");
                stmt1.setInt(1, Rs.getInt(1));
                stmt1.setString(2, "ram@mi.com");
                stmt1.setString(3, "123456789");
                stmt1.execute();
            }
        } catch (ClassNotFoundException | SQLException ex) {
            System.out.println("Ex : " + ex.getMessage());
        }
    }
}

Output:



Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment