2011-08-16 45 views
0

我想讓我的頭瞭解如何使用Flex/Actionscript 3(使用Adobe Air 2)中的事務執行SQLite批量插入。這工作,但它沒有意義的循環重新創建一個新的SQLStatement:Actionscript SQLite在事務中插入語句

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文本,這正是我試圖避免的。我確信有更好的方法來做到這一點,但我花了太長時間的黑客攻擊和閱讀,試圖找出正確的順序。有任何想法嗎?

+0

是否有一個原因,你不能有一個語句,但增量參數的所有插入?即。 「@NAME1」,「@ NAME2」等 –

+0

SQLite不支持「INSERT到聯繫人(姓名,姓氏)VALUES('Frank','Furter'),('Jack','Horner'),('Bo' ,'Peep')「? –

回答

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()方法將在結果處理程序中調用;當數組爲空時,你會提交;你的錯誤處理程序會發出回滾。