Advertisement
Guest User

Untitled

a guest
Mar 7th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. //Connection jdbc in java mysql
  2. //When we are inserting a record into the database table and the primary
  3. // key is an auto-increment or auto-generated key, then the insert query will
  4. // generate it dynamically. The below example shows how to get this key after
  5. // insert statement. After perfoming executeUpdate() method on PreparedStatement,
  6. // call getGeneratedKeys() method on PreparedStatement. It will return you ResultSet,
  7. // from which you can get auto increment column values.
  8.  
  9.  
  10. package jdbcdemo;
  11. import java.sql.*;
  12.  
  13. /**
  14. *
  15. * @author yashy
  16. */
  17. public class JDBCDemo {
  18.  
  19. public static void main(String[] args) throws Exception {
  20. ResultSet rs;
  21. String url = "jdbc:mysql://localhost:3306/students";
  22. //Load register and driver
  23. Class.forName("com.mysql.cj.jdbc.Driver");
  24. //Create connection
  25. Connection con =DriverManager.getConnection(url,"root","");
  26. //Create statement
  27. //Statement st = con.createStatement();
  28. //update query
  29. String query = "insert into std_details(name, password,email) values(?,?,?); ";
  30.  
  31. PreparedStatement prst = con.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
  32. prst.setString(1, "ram");
  33. prst.setInt(2, 544);
  34. prst.setString(3, "ram@gmail.com");
  35.  
  36. prst.executeUpdate();
  37. rs = prst.getGeneratedKeys();
  38. if(rs != null && rs.next()){
  39. System.out.println("Generated Id: " + rs.getInt(1));
  40. }
  41.  
  42.  
  43. }
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement