用Mysql检索上次插入的id
美好的一天,
我愿意在Mysql中检索新插入的行的id值。
我知道有mysqli_insert_id函数,但是:
- 我无法指定表格
- 如果同时进行查询,也许会有检索错误ID的风险。
- 我正在使用node.js MySQL
我不想冒险查询最高的ID,因为有很多的查询,它可以给我错误的…
(我的ID列在自动增量)
https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row完美地描述了解决scheme:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) { if (err) throw err; console.log(result.insertId); });
编辑:拼写和repo在github中移动,所以我改为当前的链接。
var table_data = {title: 'test'}; connection_db.query('INSERT INTO tablename SET ?', table_data , function(err, result, fields) { if (err) { // handle error }else{ // Your row is inserted you can view console.log(result.insertId); } });
您也可以通过访问此链接查看https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
我想你误解了mysqli_insert_id()
方法的使用。 这个方法必须在insert语句之后立即执行,以获得最后插入的id。 如果你直接做我的MySQL
INSERT INTO(a,b)values(1,'test'); SELECT LAST_INSERT_ID(); -- this will display the last inserted id