2010-09-22 67 views
1

我有一個文件,其中包含多個SQL語句以便執行。Flex:多個插入調用的sqlite last_insert_rowid

INSERT INTO reports (a,b,c) VALUES (1,2,3); 

INSERT INTO units (report_id, e, f, g) VALUES ((SELECT last_insert_rowid() FROM reports), 4, 5, 6); 

INSERT INTO elements (report_id, h, i, j) VALUES ((SELECT last_insert_rowid() FROM reports), 7, 8, 9); 

子選擇的從報告中節什麼也不做。

什麼結束了發生的事情是:

  1. 一個行插入到報告和reports.id場自動增量
  2. 一行插入單位REPORT_ID等於報告ID
  3. 將行插入元素中,其中report_id等於插入的最後一行的units.id

這是按照sqlite文檔中所述的方式工作的。

我的問題是,我希望報告插入後面的所有查詢都使用report.id。

無論如何,我可以得到這個在數據庫端工作,而不必訴諸在AS3解決方案?

回答

2

有一種方法可以做到這一點,但它在AS3中使用參數。

所做的是在每次調用中使用SELECT last_insert_row()函數,而不是使用參數替換它。

INSERT INTO elements (report_id, h, i, j) VALUES (@id, 7, 8, 9); 

現在在我的代碼,我必須將文件分割成一個陣列,使每個人的查詢是單獨的過程(這是AS3如何實現的SQLite的API)。

var sqlArray:Array = sql.split(";\n\n"); 

現在我所做的是執行第一條語句來導入報表本身。

statement.text = sqlArray[0]; 
statement.execute(); 

現在有趣的部分。你需要把ID退出。所以我們運行另一個查詢。

statement.text = "SELECT last_insert_rowid() as ID"; 
statement.execute(); 
var id:int = statement.getResult().data[0].id; 

現在我們可以使用id作爲參數循環查看其餘的查詢。

for(var i:int = 1; i < sqlArray.length - 1; i++) { 
    /** 
    * start at 1 because we already inserted the report 
    * end at length -1 because our last entry is empty because of how split works on our data 
    **/ 
    statement.text = sqlArray[i]; 
    statement.parameters['@ID'] = id; 
    statement.execute(); 
} 

這是一個更復雜一點,但不是很多,它結束了工作。

一切告成成一個單一的功能(省略了很多類的開銷)是:

function importFromSQLString(sql:String):void { 
    try{ 
    connection.begin(); 
    var sqlArray:Array = sql.split(";\n\n"); 
    statement.text = sqlArray[0]; 
    statement.execute(); 

    statement.text = "SELECT last_insert_rowid() as ID"; 
    statement.execute(); 
    var id:int = statement.getResult().data[0].id; 

    for(var i:int = 1; i < sqlArray.length - 1; i++) { 
     statement.text = sqlArray[i]; 
     statement.parameters['@ID'] = id; 
     statement.execute(); 
    } 
    connection.commit(); 
    statement.clearParameters(); 
    } catch (e:Error) { 
    connection.rollback(); //cleanup if there was a failure 
    } 
}