mysql 取最后一次登陆,获得最后一次插入mysql的id | 学步园
最近兩天一直忙著通過數(shù)據(jù)庫訪問數(shù)據(jù)記錄,然后做操作。以前我在數(shù)據(jù)庫中插入記錄后,就要去做別的操作,別的操作也是先訪問存在數(shù)據(jù)庫中的記錄,然后完成操作。所以我通過記錄的名字來訪問記錄的,原來想過通過id來訪問數(shù)據(jù)庫,但是當(dāng)時不知道怎么來獲得數(shù)據(jù)庫的id,只有通過記錄名來訪問。但這樣做還是有點問題,在英文環(huán)境下可以查詢到正確的記錄,但是在中文下,插入到數(shù)據(jù)庫中的就會出現(xiàn)???亂碼,萬般無奈下,同事說,如果建表語句中的id是auto_increment的,就可以在插入數(shù)據(jù)庫后就獲得最后一次插入數(shù)據(jù)庫的id,所以現(xiàn)在修改成了通過id來查詢數(shù)據(jù)庫記錄,并完成其它的操作,不受中文的限制了。
現(xiàn)在說說具體的操作吧:
public static final String InsertScheduleSearchStr = "insert into scheduleSearch(scheduleSearchName,scheduleInfo,createTime,mailSendTo,scheduleDays,scheduleHours,scheduleMinutes) values(?,?,?,?,?,?,?)";
public static final String LastInsertId = "select last_insert_id() as scheduleSearchId from scheduleSearch limit 1";
stmt = (PreparedStatement) dbMgr.getStatement(InsertScheduleSearchStr);
if (stmt == null) stmt = con.prepareStatement(InsertScheduleSearchStr);
String scheduleSearchName = xmlScheduleSearch.getScheduleSearchName();
stmt.setString(index++,scheduleSearchName);
stmt.setBytes(index++, xmlScheduleSearch.getScheduleSearchBytes());
java.util.Date now = new java.util.Date();
stmt.setTimestamp(index++, new Timestamp(now.getTime()));
stmt.setString(index++,xmlScheduleSearch.getSendMailTo());
stmt.setInt(index++,xmlScheduleSearch.getScheduleDays());
stmt.setInt(index++,xmlScheduleSearch.getScheduleHours());
stmt.setInt(index++,xmlScheduleSearch.getScheduleMinutes());
stmt.executeUpdate();
dbMgr.saveStatement(InsertScheduleSearchStr, stmt);
stmt = (PreparedStatement) dbMgr.getStatement(LastInsertId);
if (stmt == null) stmt = con.prepareStatement(LastInsertId);
rs = stmt.executeQuery();
int scheduleSearchId = 0;
if (rs.next())
{
scheduleSearchId = rs.getInt(1);
}
主要的語句就是通過mysql中的mysql_insert_id() 完成取最后一次插入數(shù)據(jù)庫的id
mysql_insert_id()用法
my_ulonglong mysql_insert_id(MYSQL *mysql)
返回由先前的查詢?yōu)橐粋€AUTO_INCREMENT列生成的ID。在你執(zhí)行一個INSERT查詢向一個包含AUTO_INCREMENT字段的表中插入后,使用這個函數(shù)。
注意,如果先前的查詢不產(chǎn)生一個AUTO_INCREMENT值,mysql_insert_id()返回0。如果你需要在以后保存該值,必須在查詢生成了該值后馬上調(diào)用mysql_insert_id()。
也要注意,SQL的LAST_INSERT_ID()函數(shù)總是包含最近生成的AUTO_INCREMENT值,并且在查詢之間不被重置,因為該函數(shù)的值在服務(wù)器端維護(hù)。
有先前的查詢更新的AUTO_INCREMENT字段的值。如果在連接上沒有先前的詢問或如果查詢沒更新AUTO_INCREMENT值,返回零。
總結(jié)
以上是生活随笔為你收集整理的mysql 取最后一次登陆,获得最后一次插入mysql的id | 学步园的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle中prad函数_等保测评2.
- 下一篇: mysql 体重 类型 身高_体重较轻,