简体   繁体   English

在节点js的sqllite数据库中批量插入class object

[英]Bulk insert class object in sqllite database in node js

I have the following class called Label:我有以下 class 称为 Label:

class Label{
    constructor(imageid, plotid, camera, date, x, y, w, h, id, hash){
      this.imageid = imageid;
      this.plotid = plotid;
      this.camera = camera;
      this.date = date;
      this.x = x;
      this.y = y;
      this.w = w;
      this.h = h;
      this.id = id;
      this.hash = hash
    }
  }

I have a list of these class objects called labels that I want to insert, or rather bulk insert into my sqllite database, which looks like the following:我有这些 class 对象的列表,这些对象称为我想要插入的labels ,或者更确切地说是批量插入到我的 sqllite 数据库中,如下所示:

db中的标签表

I tried to insert this array of class objects with:我试图插入这个 class 对象数组:

function addRowsToDb(){
    console.log("Adding rows to the db")
    db = new sqlite3.Database('./annotator.db');
    db.serialize(function() {

        var stmt = db.prepare("INSERT INTO Label(ImageID, PlotID, Camera, Date, x, y, w, h, LabelHash) VALUES (?,?,?,?,?,?,?,?,?)");
        labels.forEach((label) => {
            stmt.run(label.imageid, label.plotid, label.camera, label.date, label.x, label.y, label.w, label.h, label.hash);
        })
        stmt.finalize();
    });
    db.close();
}

Which gave me the following errors in the console:这在控制台中给了我以下错误:

Uncaught Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: Label.ImageID未捕获的错误:SQLITE_CONSTRAINT:NOT NULL 约束失败:Label.ImageID

Uncaught Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: Label.LabelHash未捕获的错误:SQLITE_CONSTRAINT:NOT NULL 约束失败:Label.LabelHash

Could someone explain to me how to do this properly and how to do this with bulk data, so not the forEach with the labels array?有人可以向我解释如何正确执行此操作以及如何使用批量数据执行此操作,而不是带有标签数组的 forEach 吗?

I think the error is pretty straight forward - you try to insert NULL values into non-nullable db columns ( Label.ImageID and Label.LabelHash ).我认为错误很简单-您尝试将NULL值插入不可为空的数据库列( Label.ImageIDLabel.LabelHash

How to solve this depends on what makes the most sense for your app:如何解决这个问题取决于什么对您的应用最有意义:

  • remove the NOT NULL constraint on those columns删除这些列上的NOT NULL约束
  • skip the labels that don't have ImageID and LabelHash set跳过没有设置ImageIDLabelHash的标签
  • provide a default value (empty string for example) for the ImageID and LabelHash colsImageIDLabelHash cols 提供默认值(例如空字符串)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM