Node.js sqlite3执行INSERT后this.lastID返回undefined解决方法
sqlite3执行INSERT后this.lastID返回undefined问题解决
问题背景
开发中参考sqlite3官方文档示例,期望执行INSERT插入操作后获取最后插入记录的自增ID,但实际运行时始终获取到undefined值,不确定是代码编写错误还是对应功能已不再支持。当前项目package.json中引入的sqlite3依赖版本为^5.0.8。
复现代码如下,回调函数内打印的this.lastID始终为undefined:
sql = `INSERT INTO comment_hearts(post_id, comment_id, user_id, CREATED_AT) VALUES (?,?,?,?)` db.run(sql, [1, 100, 10, new Date().toString()], (err) => { if (err) { console.log(err.message)}; console.log("THIS.lastID",this.lastID) // 始终返回undefined });
故障原因
- sqlite3从5.0版本开始做了破坏性变更:
db.run的回调不再通过this挂载lastID、changes属性,而是将这两个值作为回调的第二、第三个参数传入。 - 代码中使用了箭头函数作为回调,箭头函数本身没有独立的
this绑定,会直接继承外层作用域的this,即便在4.x及更早版本中,这种写法也无法拿到正确的this.lastID值。
修复方案
直接从回调参数中获取lastID即可,兼容5.x及以上版本,同时箭头函数、普通函数写法都可正常使用:
const sql = `INSERT INTO comment_hearts(post_id, comment_id, user_id, CREATED_AT) VALUES (?,?,?,?)` db.run(sql, [1, 100, 10, new Date().toString()], (err, lastID, affectedRows) => { if (err) { console.log(err.message); return; } console.log("最后插入记录的自增ID:", lastID); console.log("本次操作影响行数:", affectedRows); });
注意:如果仍在使用4.x及更早版本的sqlite3,需要将回调改为普通函数(不能用箭头函数),才能通过
this.lastID拿到对应值,该写法在5.x版本已失效。
// 仅适用于sqlite3 4.x及更早版本 db.run(sql, [1, 100, 10, new Date().toString()], function (err) { if (err) { console.log(err.message); return; } console.log("最后插入记录的自增ID:", this.lastID); });
内容的提问来源于stack exchange,提问作者Maik Lowrey
相关产品推荐
相关产品推荐

