MySQL語句:獲取最後一條記錄(ID數值最大的) - - Java EE
阿新 • • 發佈:2019-01-07
使用升序排序,將ID數值最大的放到最頂部。並顯示出來。
order by % desc 表示按降序排序
在sql語句的最後加上 limit 0,1 只取第一條記錄
select * from 表名 order by 表中ID欄位名稱 desc limit 0,1;
如:
select * from role order by role_id desc limit 0,1;
例項:
使用limit 0,1後
limit知識點及使用方法: limit 偏移量,每次顯示的記錄數量 如:limit 15,10 意思就是從第15條資料開始顯示,顯示10條 **注:limit必須接在sql語句的最後!!!**
Java EE 獲取這個最大的ID值
我的JDBC環境已搭好
String sql = "select * from role order by role_id desc limit 0,1"; ResultSet rs = db.executeQuery( sql, null ); //自己建的執行SQL語句方法executeQuery(),返回一個結果集 Integer Max_roleId = null; //存放最大ID值 try { if ( rs!=null && rs.next() ) { Max_roleId = rs.getInt(1)+1; //獲取結果集中第一個欄位的最大ID值+1,給下一個ID } //後面可以使用insert 語句使用Max_roleI //在此不再演示 } catch (SQLException e) { e.printStackTrace(); } finally { db.sqlClose(); //關閉資料庫 }