Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Connection jdbc in java mysql
- //When we are inserting a record into the database table and the primary
- // key is an auto-increment or auto-generated key, then the insert query will
- // generate it dynamically. The below example shows how to get this key after
- // insert statement. After perfoming executeUpdate() method on PreparedStatement,
- // call getGeneratedKeys() method on PreparedStatement. It will return you ResultSet,
- // from which you can get auto increment column values.
- package jdbcdemo;
- import java.sql.*;
- /**
- *
- * @author yashy
- */
- public class JDBCDemo {
- public static void main(String[] args) throws Exception {
- ResultSet rs;
- String url = "jdbc:mysql://localhost:3306/students";
- //Load register and driver
- Class.forName("com.mysql.cj.jdbc.Driver");
- //Create connection
- Connection con =DriverManager.getConnection(url,"root","");
- //Create statement
- //Statement st = con.createStatement();
- //update query
- String query = "insert into std_details(name, password,email) values(?,?,?); ";
- PreparedStatement prst = con.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
- prst.setString(1, "ram");
- prst.setInt(2, 544);
- prst.setString(3, "ram@gmail.com");
- prst.executeUpdate();
- rs = prst.getGeneratedKeys();
- if(rs != null && rs.next()){
- System.out.println("Generated Id: " + rs.getInt(1));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement