1

我目前有一个尝试将数据插入表的事务。如果数据已经在表中,则会引发约束失败错误并运行选择以获取 ID。

t2.executeSql('INSERT INTO books (book) VALUES (?);',
  [record],
  function (t2, r) {        // SQL_successfulCallback
    record = r.insertId;
  },
  function (t2, err) {      // SQL_errorCallback
    if (err.message !== 'constraint failed') { // insert failed because of other
                                               // reason - fail transaction
      console.log('Insert SQL error ' + err.code + ' - ' + err.message + '.');
      return true;
    } else { // insert failed because data was already in the table
      t2.executeSql('SELECT bookID FROM books WHERE book=?',
        [record],
        function (t, r) {   // SQL_successfulCallback
          record = r.rows.item(0).classificationID;
        },
        function (t, err) { // SQL_errorCallback
          console.log('Lookup SQL error ' + err.code + ' - ' + err.message + '.');
          return true;
        }
      );
      return false;
    }
  }
);

我想加快交易速度,所以我想我会先看看数据是否在表中。如果不是,则插入它...

t2.executeSql('SELECT bookID FROM books WHERE book=?',
  [record],
  function (t2, r) {          // SQL_successfulCallback
    if (r.rows.length !== 0) {
      record = r.rows.item(0).bookID;
    } else {
      t2.executeSql('INSERT INTO books (book) VALUES (?);',
        [record],
        function(t2, r){      // SQL_successfulCallbac
          record = r.insertId;
        },
        function (t2, err) {  // SQL_errorCallback
          if (err.message !== 'constraint failed') { // insert failed because of other
                                                     // reason - fail transaction
            console.log('Insert SQL error ' + err.code + ' - ' + err.message + '.');
            return true;
          } else { // insert failed because data was already in the table
            return false;
          }
        }
      );
    }
  },
  function (t, err) {         // SQL_errorCallback
    console.log('Lookup SQL error ' + err.code + ' - ' + err.message + '.');
    return true;
  }
);

...但它不起作用。该事务运行所有选择,然后执行插入。我怎样才能使第二种方法起作用?

4

1 回答 1

0

我假设事务正在排队请求。所以你的队列看起来像这样

选择 1

选择 2

选择 3

然后,当您提交您的事务时,第一次调用后看起来像这样。

选择 2

选择 3

插入 1

插入 2

插入 3

This is happening because the the functions to call the inserts are exected after the select is ran and this doesn't happen until the transaction commits but the selects have already be registered.

In order to get it to be

select1

insert1

select2

insert2

I would create a separate transaction for each select statement.

于 2011-10-31T03:26:51.057 回答