mysql - Node js不会在mysql表中插入主键

标签 mysql sql node.js express mysql2

如何在 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")
    }
);

检查下面的输出,

Output

关于mysql - Node js不会在mysql表中插入主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59964895/

相关文章:

sql - 你使用了哪些编码技巧来避免编写更多的 sql?

java - 该查询的 Hibernate 等效项是什么?(添加两列)

javascript - 回调不是 Node js中的函数

javascript - 如何从 Node.js 启动桌面应用程序?

php - 获取单个数据库调用中的所有数据并在 Controller 中过滤它 - Codeigniter?

mysql连接值之间的差异最小?

java - SQL 查询 1 :n relation, 查找具有两个匹配子项的所有实体

node.js - sails js 中的当前 session ID

php - PHP OOP 中的未定义属性错误消息

mysql - 用两个不同的列加入同一个表 laravel