gpt4 book ai didi

sqlite - 如何在Ionic 2和SQLite上处理事务和相关记录?

转载 作者:行者123 更新时间:2023-12-03 19:24:58 26 4
gpt4 key购买 nike

我正在使用SQLite创建Ionic 2应用程序。我已经能够成功执行命令,创建表并在数据库中插入记录。现在,我正在尝试插入一些父记录和明细记录,并且我想在事务内进行此操作,以便在插入子记录时发生任何错误时,父记录不会损坏。

好了,根据此链接(https://github.com/litehelpers/Cordova-sqlite-storage),我可以通过以下方式使用事务:

db.transaction(function(tx) {
tx.executeSql("Insert into ParentTable(ParentName) values ('name')");
tx.executeSql("Insert into ChildTable(ParentID, ChildName) values (0, 'value1')");
}, function(error) {
console.log('Transaction ERROR: ' + error.message);
}, function() {
console.log('Transaction OK');
});


问题是我需要从第一个插入中获取ParentID才能在第二个插入中使用。 insertSQL命令具有一个callback,因此我编写了以下代码:

db.transaction(function(tx) 
{
tx.executeSql("Insert into ParentTable(ParentName) values ('name')",
function(tx, rs)
{
/* Location 1 */
var parentID = rs.insertId;
tx.executeSql("Insert into ChildTable(ParentID, ChildName) values (?, 'value1')", [parentID]);
});
/* Location 2 */
}, function(error) {
console.log('Transaction ERROR: ' + error.message);
}, function() {
console.log('Transaction OK');
});


因此,我有疑问。由于executeSql是异步的,因此位置2将在位置1之前执行。
问题是: db.transaction超出范围时,事务将在位置2之后完成吗?
如果是,则位置1将在事务完成后执行,那么如何使其在事务内执行?

如果否,它将何时提交或回滚?

最佳答案

您必须使用promise来级联两个异步任务。

关于sqlite - 如何在Ionic 2和SQLite上处理事务和相关记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45406601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com