【问题标题】:Sqlite3 is not inserting multiple rows in orderSqlite3 没有按顺序插入多行
【发布时间】: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


【解决方案1】:

关系中没有顺序

关系中没有顺序(即人们通常错误地称为“表”),因为关系是一个集合,而不是列表或数组。

如果人们没有错误地将关系称为“表格”,那么没有人会期望他们会下订单。不幸的是,他们这样做导致了无数常见的误解,以至于我写了一篇文章:

简而言之 - 不要期望任何集合中的任何顺序(这包括关系)。如果您需要订单,请在 SQL 中使用sort。如果你想要一个特定的顺序,添加一个整数值,你可以排序以获得你需要的顺序。

(或者不要使用关系数据库 - 还有其他类型的数据库支持数组等排序结构。关系数据库不支持数组 - 至少它们不应该 - 并且在任何关系中都没有隐含的顺序。 )

【讨论】:

  • 我为整数创建了一个单独的列,其中包含订单号,并且在获取数据期间我在查询中使用了 order by。成功了,谢谢!
猜你喜欢
  • 2018-04-17
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多