【问题标题】:HTML5, SQLite transaction questionHTML5、SQLite 事务问题
【发布时间】:2011-06-19 10:22:02
【问题描述】:

在我的 HTML5 中,我有一个 for 循环,它调用一个函数来插入数据库。我需要这个函数在单个事务中。

function Ins(id){
db.transaction(function(tx){
tx.executeSql('insert into Product(id) values(?);', [iName], function() {}, function() { });
}); 
}

for循环

    db.transaction(function(tx){tx.executeSql("BEGIN",[]);});
    for (intCountLine=1;intCountLine<=1000;intCountLine++)
    {
    Ins(intCount);
    }
   db.transaction(function(tx){tx.executeSql("COMMIT",[]);});

你可以看到,我有事务开始和提交,但我假设当它调用 INS 函数时,它会打开一个新事务并关闭它,每次调用它。我如何确保不会发生这种情况。

用谷歌搜索但找不到它...在这里给我一些亮点....

【问题讨论】:

    标签: javascript sqlite transactions cordova


    【解决方案1】:

    这可能会奏效。使用 insert select union all 而不是创建 1000 个插入语句。但这一次只能插入 500 行。这是我编写的代码,在 Google chrome 上进行测试,我确信它可以工作。

    <!DOCTYPE HTML>
    <html>
    <head>
    <script type="text/javascript">
    var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
    var msg;
    var j=1;
    var i=1;
    var quer="";
    db.transaction(function(tx){tx.executeSql("CREATE TABLE IF NOT EXISTS LOGS (ID INTEGER PRIMARY KEY ASC, todo TEXT)",[]);});
    db.transaction(function(tx){tx.executeSql("delete from logs",[]);});
    txquer();
    showMsg();
    function txquer()
    {
      quer="insert into logs ";
     for(i=j;i<=j+498;i++)
     {
      quer+=" select "+i+",'test' union all";
      }
      quer+=" select "+i+",'test' ; ";
      j=i+1;
        db.transaction(
        function(tx){
          tx.executeSql(quer,[]);    
        }
        );
    
    }
    
    function showMsg(){
    db.transaction(function (tx) {
      tx.executeSql('SELECT count(*) todo FROM LOGS', [], function (tx, results) {
       var len = results.rows.item(0).todo;
       msg = "<p>Found rows: " + len + "</p>";
       document.querySelector('#status').innerHTML +=  msg;  
     }, null);
    });
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多