Actionscript SQLite在事务中插入语句

时间:2011-08-16 18:12:09

标签: flash flex sqlite actionscript transactions

我正试图了解如何使用Flex / Actionscript 3中的事务(使用Adobe Air 2)进行SQLite批量插入。这样可行,但在循环中重新创建新的SQLStatement没有意义:

private function onAddBulkContacts():void {
_responder = new Responder(resultEventHandler, errorEventHandler);
contacts_db.connection.begin(null, _responder);
var statement:SQLStatement;

for (var i:uint=0; i<parseInt(bulkAdd.numberToAdd.text); i++) {
 statement  = new SQLStatement();
statement.sqlConnection = contacts_db.connection;
statement.text ="INSERT INTO contacts ('name', 'lastname') VALUES (@NAME, @LASTNAME)";

statement.addEventListener(SQLErrorEvent.ERROR, function(event:Event):void {
trace('statement error');});
statement.addEventListener(SQLEvent.RESULT, function(event:Event):void { trace('result'); });
    statement.parameters['@NAME'] = "Name " + i.toString();
    statement.parameters['@LASTNAME'] = "LastName " + i.toString();
    statement.execute();   
}
contacts_db.connection.commit();
}

我想要做的是创建一次SQLStatement,让它编译,然后在循环中传递新参数,最后提交它,例如

private function onAddBulkContacts():void {
_responder = new Responder(resultEventHandler, errorEventHandler);
contacts_db.connection.begin(null, _responder);
var statement:SQLStatement;

statement  = new SQLStatement();
statement.sqlConnection = contacts_db.connection;
statement.text ="INSERT INTO contacts ('name', 'lastname') VALUES (@NAME, @LASTNAME)";

statement.addEventListener(SQLErrorEvent.ERROR, function(event:Event):void {
trace('statement error');});
statement.addEventListener(SQLEvent.RESULT, function(event:Event):void { trace('result'); });

for (var i:uint=0; i<parseInt(bulkAdd.numberToAdd.text); i++) {
    statement.parameters['@NAME'] = "Name " + i.toString();
    statement.parameters['@LASTNAME'] = "LastName " + i.toString();
    statement.execute();   
}
contacts_db.connection.commit();
}

但是后一个代码抛出一个错误,说它不能执行第二次,因为语句本身仍在执行(我相信在提交之前将处于该状态)。我想我可以理解这些语句被添加到执行队列中,但是我不得不在循环中添加SQL文本,这正是我想要避免的。我确信有更好的方法可以做到这一点,但我已经花了太长时间黑客和阅读试图弄清楚正确的顺序是什么。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尚未在AIR中进行批量插入,但通常会在循环外创建语句,启动事务;然后循环的每次迭代绑定新的参数值并执行语句;然后在循环之外,提交。

数据库是以同步还是异步方式打开的?

在异步模式下:

... the simplest way to organize the application to ensure that the operations are executed properly is to create a method that’s registered as a listener for the begin event. The code to call the SQLStatement.execute() method is placed within that listener method. http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7d2b.html

您还可以尝试使用array.shift()方法而不是在循环中将下一组值绑定到语句参数;将在结果处理程序中调用array.shift()方法;当数组为空时你会提交;你的错误处理程序会发出回滚。