【发布时间】:2017-01-23 11:54:37
【问题描述】:
我正在使用 node js 应用程序,数据库是 sqlite3 (2.15.8)。我正在使用 sqlite3 module 。在此我必须按顺序插入行。
我有表tests,其中的行应该按照它们进入循环的相同顺序插入。
我的代码如下:
创建表格:
GLOBAL.db1 = new sqlite3.Database(APPDATA+'/xyz/mydb.db');
var check;
db1.serialize(function() {
db1.run("CREATE TABLE IF NOT EXISTS tests (id INTEGER NOT NULL PRIMARY KEY , parent_name varchar(255), test_name varchar(255), test_alias varchar(255), sequences varchar(55), duration varchar(55), prog_id int(11), org_id int(11), test_createdby int(11), test_created varchar(20), test_modified varchar(11), test_status int(11))");
});
插入表格
try{
db1.run("INSERT INTO programs (`prog_name`, `prog_exercises`, `prog_orgid`, `prog_createdby`, `prog_created`, `prog_modified`, `prog_status`) VALUES (?,?,?,?,?,?,?)",program_name, JSON.stringify(step2PostedData), org_id, createdby, timestamp, timestamp, 0,function(err){
// as it is single record insertion so inserting good obviously.
if(err){
throw err;
}else{
for (i in step2PostedData.testsInfo) {
var c = 0;
for(j in step2PostedData.testsInfo[i]){
var obj = Object.keys(step2PostedData.testsInfo[i])[c];
console.log(obj); // here I am getting correct order of test names in console
db1.prepare("INSERT INTO `tests` ( `parent_name`,`test_name`, `test_alias`, `sequences`, `duration`, `prog_id`, `org_id`, `test_createdby`, `test_created`, `test_modified`, `test_status`) VALUES(?,?,?,?,?,?,?,?,?,?,?)").run('', obj, step2PostedData.testsInfo[i][j].alias, step2PostedData.testsInfo[i][j].sequences, step2PostedData.testsInfo[i][j].duration, this.lastID, org_id, createdby, timestamp, timestamp, 0);
// Insertion is going in loop but order of insertion of rows is not same as per required
c++;
}
}
}
});
}catch(ex){
throw ex;
}
但是,当我在表格中得到结果时,tests 表格中插入的行顺序与我发送到循环中的顺序不同。 谁能建议我什么应该在那里改吗?
谢谢!
【问题讨论】:
-
对于大多数 RDBMS,您不能期望 任何 特定顺序,除非您使用 ORDER BY 明确请求一个。如果没有任何顺序,您按照插入它们的顺序返回记录——那纯属巧合,您不应该依赖任何东西。
-
但是在console.log(obj);就在插入之前,我得到了我喜欢插入的正确顺序。我们可以使用 Order by there 插入吗?请建议,如果是,那么如何???
-
插入记录的顺序无关紧要。当您读取数据库中的记录时,您需要指定一个明确的顺序标准。
-
订单在插入过程中始终是动态的。你能在这里建议或回答吗?
标签: node.js sqlite android-sqlite