我有方法在数据库中搜索最大的 id 并返回该 id + 1
static int searchIdNewPlane(Connection con) {
int maxId = 1;
try {
String query = "SELECT id FROM Plane ORDER BY id DESC Limit 1 ";
PreparedStatement pst = con.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
maxId = rs.getInt("id");
}
return maxId + 1;
} catch (Exception e) {
return 1; //error
}
}
这是解决问题的好主意吗?
最佳答案
根据数据库,更好的解决方案是使用序列。这种方法有一些固有的问题(不是线程安全的,...)。
关于Java - 搜索数据库表中的最大ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27064555/