如何获取java mysql中的最后一个插入ID

时间:2019-01-09 16:12:55

标签: java

我正在创建简单的销售系统。我必须获取最后一个插入ID,但无法获取ID。尝试代码时出现控制台错误 java.sql.SQLException:无法使用executeQuery()发出数据操作语句。  我在到目前为止尝试过的代码下面附加了代码

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);
}

1 个答案:

答案 0 :(得分:0)

您需要在Statement.RETURN_GENERATED_KEYS中添加con1.prepareStatement(query),这将导致您可以获取生成的密钥。您还应该仅使用以下方法之一:

  • executeQuery
  • executeUpdate

因为没有理由,所以要使用展位方法。

完成后,您可以像这样获得它:

...
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);
...