我有以下名为 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
}
}
我有一个名为 labels
的类对象列表,我想将其插入,或者批量插入到我的 sqllite 数据库中,如下所示:
我尝试插入这个类对象数组:
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();
}
这在控制台中给了我以下错误:
Uncaught Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: Label.ImageID
Uncaught Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: Label.LabelHash
有人可以向我解释如何正确执行此操作以及如何使用批量数据执行此操作,而不是使用带有标签数组的 forEach 吗?
最佳答案
我认为错误非常简单 - 您尝试将 NULL
值插入不可为空的数据库列(Label.ImageID
和 Label.LabelHash
)。
如何解决这个问题取决于什么对您的应用最有意义:
- 删除这些列上的
NOT NULL
约束 - 跳过未设置
ImageID
和LabelHash
的标签 - 为
ImageID
和LabelHash
列提供默认值(例如空字符串)
关于javascript - 在node js中的sqlite数据库中批量插入类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58627029/