【问题标题】:Node js doesnt insert primary key in mysql tableNode js不在mysql表中插入主键
【发布时间】:2020-05-14 19:42:52
【问题描述】:

如何在节点js表中插入主键?主键是 AUTO_INCREMENT,据我所知,我不应该将任何东西从节点 js 传递到 DB 以获取 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”

【问题讨论】:

  • 你用哪个npm包连接MySQL?
  • @GokulaKannan T, Express, mysql2

标签: mysql sql node.js express mysql2


【解决方案1】:
CREATE TABLE `table` (`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `post_ID` bigint(20) unsigned NOT NULL DEFAULT 0, `author` tinytext NOT NULL,PRIMARY KEY 
 (`ID`))

【讨论】:

  • 已经是这样了,但插入时 id 仍然为空。它不会增加。
【解决方案2】:

我相信,PRIMARY KEY 在表创建中丢失了。

另外,我建议使用不同的名称而不是 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,我使用下面的sn-p来做到这一点。

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

检查下面的输出,

【讨论】:

  • 这是我的表的完整导出,如您所见,"comment_id" 'CREATE TABLE wpil_comments (comment_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT, @987654330 @ bigint(20) unsigned NOT NULL DEFAULT 0, comment_author tinytext NOT NULL, PRIMARY KEY (comment_ID), ) ENGINE=MyISAM AUTO_INCREMENT=3867 DEFAULT CHARSET=utf8;'
  • 请告诉我您机器上安装的 MySQL 版本?
  • 10.3.15-MariaDB
  • 那我们为什么要用mysql2而不是mariadb(npmjs.com/package/mariadb)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
相关资源
最近更新 更多