zoukankan      html  css  js  c++  java
  • 使用MySQL的LAST_INSERT_ID--转

    LAST_INSERT_ID

    自动返回最后一个 INSERT 或 UPDATE 操作为 AUTO_INCREMENT 列设置的第一个发生的值. 参考这里 

    The ID that was generated is maintained in the server on a per-connection basis.

    LAST_INSERT_ID是基于单个connection的, 不可能被其它的客户端连接改变。

     可以用 SELECT LAST_INSERT_ID(); 查询LAST_INSERT_ID的值.

    Important: If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only.

    使用单INSERT语句插入多条记录,  LAST_INSERT_ID只返回插入的第一条记录产生的值. 比如

    1. mysql> INSERT INTO t VALUES (NULL, 'aaaa'), (NULL, 'bbbb'), (NULL, 'cccc');   
    2. mysql> SELECT * FROM t;   
    3. +----+------+   
    4. | id | name |   
    5. +----+------+   
    6. |  1 | Bob  |   
    7. |  2 | aaaa |   
    8. |  3 | bbbb |   
    9. |  4 | cccc |   
    10. +----+------+   
    11. mysql> SELECT LAST_INSERT_ID();   
    12. +------------------+   
    13. | LAST_INSERT_ID() |   
    14. +------------------+   
    15. |                2 |   
    16. +------------------+  

    ID 2 是在插入第一条记录aaaa 时产生的.

    LAST_INSERT_ID 是与table无关的,如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID会改变。

    一般情况下获取刚插入的数据的id,使用select max(id) from table 是可以的。

    但在多线程情况下,就不行了。在多用户交替插入数据的情况下max(id)显然不能用。

    这就该使用LAST_INSERT_ID了,因为LAST_INSERT_ID是基于Connection的,只要每个线程都使用独立的Connection对象,LAST_INSERT_ID函数将返回该Connection对AUTO_INCREMENT列最新的insert or update操作生成的第一个record的ID。这个值不能被其它客户端(Connection)影响,保证了你能够找回自己的 ID 而不用担心其它客户端的活动,而且不需要加锁。

    原文:http://wangcheng.iteye.com/blog/54293

  • 相关阅读:
    BIND_MISMATCH导致过多VERSION COUNT的问题
    Using dbms_shared_pool.purge to remove a single task from the library cache
    SQL Server 2012 新的分页函数 OFFSET & FETCH NEXT
    How to delete expired archive log files using rman?
    Oracle利用external table 查看trace文件
    全栈开发经验
    ASP.NET Core教程:使用Supervisor做ASP.NET Core应用程序守护进程
    ASP.NET Core教程:ASP.NET Core程序部署到Linux
    ASP.NET Core教程:ASP.NET Core 程序部署到Windows系统
    C#:窗体传值
  • 原文地址:https://www.cnblogs.com/davidwang456/p/3945533.html
Copyright © 2011-2022 走看看