如何在 Node js 表中插入主键?主键是 AUTO_INCRMENT,据我所知,我不应该将任何内容从 Node js 传递到数据库以获取 ID。
这是我的表格:
`CREATE TABLE `table` (`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `post_ID` bigint(20) unsigned NOT NULL DEFAULT 0, `author` tinytext NOT NULL)`
这是我的 MySQL 插入代码部分
dbConnection.query('INSERT INTO table (post_ID, author) VALUES (?,?);', [post_ID, author],
(err, results) => {
if (err) {
return reject(err);
};
return resolve(results.insertId);
});
仍然在我的新行中,我的 ID 为“null”
最佳答案
我相信,表创建过程中缺少主键
。
此外,我建议使用不同的名称而不是 table
,该名称当前存在于表创建查询中。
CREATE TABLE tableName (id bigint(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY, post_id bigint(20) NOT NULL DEFAULT 0, author tinytext NOT NULL);
通过上面的表格,我可以获得自动增量 id,我使用下面的代码片段来做到这一点。
connection.execute(
'INSERT INTO tableName (post_id, author) VALUES (?,?);',
[1212, "Third Author"],
function(err, results, fields) {
console.log(results); // results contains rows returned by server
res.send("Inserted Successfully")
}
);
检查下面的输出,
关于mysql - Node js不会在mysql表中插入主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59964895/