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Ö»·µ»Ø²åÈëµÄµÚÒ»Ìõ¼Ç¼²úÉúµÄÖµ. ±ÈÈç
mysql> INSERT INTO t VALUES (NULL, 'aaaa'), (NULL, 'bbbb'), (NULL, 'cccc');
mysql> SELECT * from t;
+----+------+
| id | name |
+----+------+
| 1 | Bob |
| 2 | aaaa |
| 3 | bbbb |
| 4 | cccc |
+----+------+
mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
| 2 |
+------------------+
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 ¶ø²»Óõ£ÐÄÆäËü¿Í»§¶ËµÄ»î¶¯£¬¶øÇÒ²»ÐèÒª¼ÓËø¡£
ÊÖ¶¯²åÈëauto_increment×ֶεÄʱºòϵͳ²¢²»»á¼Ç¼µ½Õâ¸öº¯ÊýÀï±ß¡£Ö»ÓÐÊÇϵͳ×Ô¶¯ÔöÒ»µÄʱºò²Å»á¼Ç¼£¡±ÈÈ磺һ¸ö±íÓ
Ïà¹ØÎĵµ£º
Class.forName("com.mySQL.jdbc.Driver");
String strUrl="jdbc:mysql://localhost:3306/stu?useUnicode=true&characterEncoding=GB2312";
String strUser="nuey";
String strPassword="password";
Connection conn=DriverManager.getCon ......
//linuxϱàÒëg++ $(mysql_config --cflags) ***.cpp $(mysql_config --libs)
/*mysqlÊý¾Ý¿âÖбíµÄÄÚÈÝ
mysql> select * from maindb;
+------------------+---------+-------------+---------+----------+---------------------+---------------------+---------------------+------------------- ......
ÏÈ¿´ÏÂÃæ×¢ÒâÄÚÈÝ
ÕûÕûŪÁËÒ»Ì죬ÖÕÓÚ½â¾öÁËjdbc(mysql-connector-java-5.0.30)ºÍmysqͨÐÅÖÐÎÄÂÒÂëµÄÎÊÌ⣡ÎÒµÄϵͳÊÇ
linux£¨ubuntu£©¡£ÔÚjavaÖУ¨Myeclipse»·¾³£©Ê¹ÓÃhibernateÁ¬½Ómysql¡£´æ´¢Ó¢ÎÄûÎÊÌ⣬д£¨insert
into£©ºÍ¶Á£¨select£©¶¼ÄÜÕýÈ·ÏÔʾ£¬µ«ÊÇÈôÆäÖдøÓÐÖÐÎÄ×Ö·û¾Í³ÉÂÒÂëÁË¡£µ½ÍøÉϲéÕÒÁË°ëÌì×ÊÁ ......