现在的位置: 首页 > 综合 > 正文

获得最后一次插入mysql的id

2013年01月02日 ⁄ 综合 ⁄ 共 2222字 ⁄ 字号 评论关闭

    最近两天一直忙着通过数据库访问数据记录,然后做操作。以前我在数据库中插入记录后,就要去做别的操作,别的操作也是先访问存在数据库中的记录,然后完成操作。所以我通过记录的名字来访问记录的,原来想过通过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值,返回零。

抱歉!评论已关闭.