还珠格格之花城公主:mysql的last_insert_id()是不是可靠的?

来源:百度文库 编辑:九乡新闻网 时间:2024/05/02 03:14:46

Mysql的API有个很有意义的函数last_insert_id()。这个函数的作用是,针对auto_increment字段,返回给定的 数据库链接,

上一步 INSERT 查询中产生的 AUTO_INCREMENT 的 ID 号。如果没有指定 数据库链接,则使用上一个打开的连接。

 

很多人质疑last_insert_id()是否是可靠的,以前我也犹豫过。

 

事实上的结果是mysql_insert_id决不会取错。首先做个测试,

在mysql_query("insert.....);之后立刻sleep(1100),其间再做些其他的insert.

然后发现在mysql_insert_id取的值都不会和其他的冲突。

 

看了半天mysql的代码。mysql_insert_id是这么定义的

 

my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql)

{

  return mysql->;last_used_con->;insert_id;

}

 

 

MYSQL是个结构体,里面包括数据库链接和一些当前数据库链接的状态值,

其中在MYSQL结构体里面有insert_id,mysql_insert_id函数返回的就是结构体里面的这个值。

 

 

typedef struct st_mysql

{

  NET net; /* Communication parameters */

  gptr connector_fd; /* ConnectorFd for SSL */

  char *host,*user,*passwd,*unix_socket,*server_version,*host_info,*info;

  char *db;

  struct charset_info_st *charset;

  MYSQL_FIELD *fields;

  MEM_ROOT field_alloc;

  my_ulonglong affected_rows;

  my_ulonglong insert_id; /* id if insert on table with NEXTNR */

  my_ulonglong extra_info; /* Used by mysqlshow */

  unsigned long thread_id; /* Id for connection in server */

  unsigned long packet_length;

  unsigned int port;

  unsigned long client_flag,server_capabilities;

  unsigned int protocol_version;

  unsigned int field_count;

  unsigned int server_status;

  unsigned int server_language;

  unsigned int warning_count;

  struct st_mysql_options options;

  enum mysql_status status;

  my_bool free_me; /* If free in mysql_close */

  my_bool reconnect; /* set to 1 if automatic reconnect */

  

  /* session-wide random string */

  char scramble[SCRAMBLE_LENGTH+1];

  

/*

   Set if this is the original connection, not a master or a slave we have

   added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()

*/

  my_bool rpl_pivot;

  /*

    Pointers to the master, and the next slave connections, points to

    itself if lone connection.

  */

  struct st_mysql* master, *next_slave;

  struct st_mysql* last_used_slave; /* needed for round-robin slave pick */

/* needed for send/read/store/use result to work correctly with replication */

  struct st_mysql* last_used_con;

  LIST *stmts; /* list of all statements */

  const struct st_mysql_methods *methods;

  void *thd;

  /*

    Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag

    from mysql_stmt_close if close had to cancel result set of this object.

  */

  my_bool *unbuffered_fetch_owner;

} MYSQL;

 

把insert_id理解成max(id)是错误的,因为有并发存在。

结构体里面有insert_id是针对当前MYSQL连接的,而每次mysql_query操作在mysql服务器上可以理解为一次“原子”操作。