用Mysql检索上次插入的ID
问题描述:
好日子,用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 介绍的解决方案非常清楚:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) {
if (err) throw err;
console.log(result.insertId);
});
Ë dit:拼写和repo在github中移动,所以我改为当前链接。
答
我想你误解了使用mysqli_insert_id()
的方法。这个方法必须在插入语句后立即执行以获得最后插入的id。如果你直接
INSERT INTO(a,b)values(1,'test');
SELECT LAST_INSERT_ID(); -- this will display the last inserted id
答
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);
}
});
您还可以查看做我的MySQL访问此链接https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
我得到一个零insertId所有的时间。有什么建议么? – Dinesh
你的表格是如何定义的?你有一个AUTO_INCREMENT ID列吗? – luksch
是的。我现在开始工作了。谢谢!这工作 – Dinesh