2015-01-08 15 views
1

我在我的項目中實現了Sqlite,在我的header.h文件和libsqlite3.dylib中添加了#import <sqlite3.h>在sqlite中傳遞數組作爲參數Swift

我怎麼能傳遞一個數組作爲參數傳遞給我的查詢,這裏就是我想:

var arrayId = [1,2] // array with interested Id 
var query:NSString = "Select id from Product where id IN \(arrayId)" // I want to select Products with id that are in the array 

編輯: 是否改變,如果是的ArrayID NSArray?因爲我也需要arrayId作爲NSArray。

然後我繼續打開sqlite數據庫,準備查詢等。

預先感謝您。

回答

1

您可以輕鬆地將數組組合成帶連接函數的字符串。

var arrayId = [1,2] // array with interested Id 
var inExpression = ",".join(map(arrayId) { "\($0)"}) 
// inExpression = "1,2" 
var query = "Select id from Product where id IN (\(inExpression))" 
+0

謝謝你的作品。如果arrayId是NSArray,我應該怎麼做? – Chongzl

+0

即使NSArray也可以用同樣的方法。 – rakeshbs

+0

是的,我明白了。謝謝 – Chongzl

0

您需要完成兩件事:將Int s的數組轉換爲String s,然後通過用逗號將它們連接起來(正如您想要使用的SQL語句)。

這裏有一個基本的功能做到了這一點:

func implode(ints: [Int]) -> String { 
    // Convert to Strings 
    let strs = ints.map { String($0) } 
    // Join Strings with commas 
    return ",".join(strs) 
} 

然後使用:

"WHERE id IN (\(implode(arrayId)))" 
0

我可能會使用類似:

var arrayId = [1,2] // array with interested Id 
var str = ",".join(arrayId.map { return "\($0)" }) 
var query = "SELECT id FROM Product WHERE id IN [\(str)]" 
+0

以這種方式我的查詢是'SELECT id FROM Product WHERE id IN [1,2]',我在SQLite Manager上執行此操作,出現錯誤:'沒有這樣的選項卡le:1,2' – Chongzl

+0

圍繞'\(str)'而不是方括號嘗試使用圓括號。我在猜測實際的SQL語法。 –

1

使用Swift自己的字符串插值創建SQL語句可能有風險(與任何語言一樣)。在sqlite3的庫提供的參數用於此目的的結合:

if (statement.prepare("SELECT name FROM products WHERE id = ?") != .Ok) { 
    // Deal with error here 
} 

// Bind the question mark to your value 
statement.bindInt(1, value: 8766) 

if (statement.step() == .Row) { 
    let name = statement.getStringAt(1) 
    // ...do something with your data from the statement 
} 

// Done. 
statement.finalizeStatement() 

編輯:

對於下面的評論,你需要()括號,而不是[]:

select id, body from test where id in (1,2); 

select id, body from test where id in [1,2]; 
+0

您的評論是有效的,但並沒有真正回答如何將IN數組作爲IN參數傳遞的問題。 –

+0

正如@大衛說,它不回答這個問題。不管怎樣,謝謝你。 – Chongzl