mysql-get上次添加的id

ktca8awb  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(192)

这个问题在这里已经有答案了

如何在jdbc中获取insert id(12个答案)
两年前关门了。
我是一个新的程序员(刚刚开始我的程序员教育)。
我试图用sql db中的最后一个id设置“tempvenueid”属性:(在本例中,idvenue=12)
表名:场馆

idvenue | name        | address
-------------------------------
 1      | Khar        | 5
 2      | SantaCruz   | 3
 3      | Sion        | 2
 4      | VT          | 1
 5      | newFort     | 3
 6      | Bandra      | 2
 7      | Worli       | 1
 8      | Sanpada     | 3
 9      | Joe         | 2
10      | Sally       | 1
11      | Elphiston   | 2
12      | Currey Road | 1

我的代码:

Private int tempVenueId;
SqlRowSet rs1 = jdbc.queryForRowSet("SELECT MAX(idvenue) FROM venue;");
while(rs1.next())tempVenueId = rs1.getInt(0);

/*I have also tried with "while(rs1.next())tempVenueId = rs1.getInt(1);"

* /

当我在intellij中运行调试模式时,它仍然不起作用:

tempVenueId = 0
lf5gs5x2

lf5gs5x21#

解决了-这个解决方法简单多了(我想是的)。

String sql = "SELECT LAST_INSERT_ID();"; 
SqlRowSet rs = Jdbc.queryForRowSet(sql);
rs.next();
Venue VN = new Venue(rs.getInt(1));
tempVenueId = VN;

现在我从db得到最后一个自动递增的et id

bfnvny8b

bfnvny8b2#

索引是从1开始的,而不是从0开始的,因此有两种方法可以解决它:

while(rs1.next()){
   tempVenueId = rs1.getInt(1);
   break;
};

SqlRowSet rs1 = Jdbc.queryForRowSet("SELECT MAX(idvenue) as value FROM venue;");
while(rs1.next()){
  tempVenueId = rs1.getInt("value");
  break;
 }

相关问题