简体   繁体   中英

how to get the last insert id in java mysql

i am creating simple sales system. i have to get the last insert id but i couldn't get the id.when i tried the code i got the error of the console java.sql.SQLException: Can not issue data manipulation statements with executeQuery(). i attached the code below what i tried so far

try{
    int lastinsertid=0;
    Class.forName("com.mysql.jdbc.Driver");   
    java.sql.Connection  con1=DriverManager.getConnection("jdbc:mysql://localhost/javasales","root","");         
    String query = " insert into sales_product (product, price)"
        + " values (?, ?)";

    // create the mysql insert preparedstatement
    PreparedStatement preparedStmt = (PreparedStatement) con1.prepareStatement(query);
    preparedStmt.setString (1, txtproduct.getText());
    preparedStmt.setString (2, txtprice.getText());

    preparedStmt.executeUpdate();       
    ResultSet rs = preparedStmt.executeQuery();
    if (rs.next()) {
        lastinsertid = (int) rs.getLong(1);
    }
    System.out.println("Inserted record's ID: " + lastinsertid);
}
catch(ClassNotFoundException coe)
{
    System.out.println("odbc driver not found");
}
catch(SQLException sqe)
{
    System.out.println(sqe);
}

You need to add Statement.RETURN_GENERATED_KEYS in con1.prepareStatement(query) that would result that you can get the generated key. You also should use only one of the following methods:

  • executeQuery
  • executeUpdate

Because there is no reason, to use booth methods.

After you done that you can get it like that:

...
PreparedStatement preparedStmt = con1.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
preparedStmt.setString (1, txtproduct.getText());
preparedStmt.setString (2, txtprice.getText());

preparedStmt.executeUpdate();
ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();

if (generatedKeyResult.next()) {
    lastinsertid = generatedKeyResult.getInt(1);
}
System.out.println("Inserted record's ID: " + lastinsertid);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM