mysql 取最后一次登陆,获得最后一次插入mysql的id | 学步园

最近两天一直忙着通过数据库访问数据记录,然后做操作。以前我在数据库中插入记录后,就要去做别的操作,别的操作也是先访问存在数据库中的记录,然后完成操作。所以我通过记录的名字来访问记录的,原来想过通过id来访问数据库,但是当时不知道怎么来获得数据库的id,只有通过记录名来访问。但这样做还是有点问题,在英文环境下可以查询到正确的记录,但是在中文下,插入到数据库中的就会出现???乱码,万般无奈下,同事说,如果建表语句中的id是auto_increment的,就可以在插入数据库后就获得最后一次插入数据库的id,所以现在修改成了通过id来查询数据库记录,并完成其它的操作,不受中文的限制了。

现在说说具体的操作吧:

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() 完成取最后一次插入数据库的id

mysql_insert_id()用法

my_ulonglong mysql_insert_id(MYSQL *mysql)

返回由先前的查询为一个AUTO_INCREMENT列生成的ID。在你执行一个INSERT查询向一个包含AUTO_INCREMENT字段的表中插入后,使用这个函数。

注意,如果先前的查询不产生一个AUTO_INCREMENT值,mysql_insert_id()返回0。如果你需要在以后保存该值,必须在查询生成了该值后马上调用mysql_insert_id()。

也要注意,SQL的LAST_INSERT_ID()函数总是包含最近生成的AUTO_INCREMENT值,并且在查询之间不被重置,因为该函数的值在服务器端维护。

有先前的查询更新的AUTO_INCREMENT字段的值。如果在连接上没有先前的询问或如果查询没更新AUTO_INCREMENT值,返回零。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值