【问题标题】:Issue with inserting data into MariaDB using NodeJS使用 NodeJS 将数据插入 MariaDB 的问题
【发布时间】:2021-03-20 06:56:37
【问题描述】:
const mariadb = require('mariadb/callback');
const connection = mariadb.createConnection({
  host     : 'localhost',
  user     : 'tudublin',
  password : 'Tudublin@2020',
  database : 'IOT',
  timezone: 'Europe/Dublin',
});
 
connection.connect(err => {
    if (err) {
      console.log("not connected due to error: " + err);
    } else {
      console.log("connected ! connection id is " + connection.threadId);
    }
  });

connection.query("INSERT INTO observations VALUES (?, ?, ?, ?)", [2, 20, "oC", Date.now()], (err, result) => {
      if (err) throw err;
      console.log(result);
      //log : { affectedRows: 1, insertId: 1, warningStatus: 0 }
    }
  );
MariaDB [IOT]> describe observations;
+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| data_id   | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| sensor_id | int(10) unsigned | NO   | MUL | NULL    |                |
| temp      | int(11)          | YES  |     | NULL    |                |
| temp_unit | varchar(30)      | YES  |     | NULL    |                |
| dt_added  | datetime         | YES  |     | NULL    |                |
+-----------+------------------+------+-----+---------+----------------+
5 rows in set (0.003 sec)

嗨,

我正在尝试将数据插入到我的观察表中。但它一直显示错误:

code: 'ER_WRONG_VALUE_COUNT_ON_ROW'

我使用以下命令创建了表

CREATE TABLE observations (data_id INT unsigned not null auto_increment primary key,sensor_id INT unsigned not null, temp int, temp_unit VARCHAR(30), dt_added DATETIME);

&

ALTER TABLE observations ADD FOREIGN KEY (sensor_id) REFERENCES sensors(sensor_id);

我认为它的设置方式很好,因为我只输入了 4 个值,另一个是设置为主键和 auto_increments 的 data_id。有人知道为什么会显示上述错误吗?

谢谢!

【问题讨论】:

    标签: javascript mysql node.js mariadb


    【解决方案1】:

    INSERT INTO observations VALUES (?, ?, ?, ?) 中,您省略了与值关联的列名,因为您需要为所有列提供值,还有主键(即使它具有自动增量)。

    插入值时通常不应仅依赖列顺序,而应使用相应的列名。如果列顺序由于某种原因发生更改,这将防止您将来出现问题,并允许您省略 data_id 列:

    INSERT INTO `observations`(`sensor_id`, `temp`, `temp_unit`, `dt_added`) VALUES (?,?,?,?) 
    

    【讨论】:

      猜你喜欢
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      • 2021-10-03
      • 2020-04-15
      • 1970-01-01
      • 2020-08-23
      相关资源
      最近更新 更多