在 sqlite Swift 中将数组作为参数传递

passing array as parameter in sqlite Swift

我通过在我的 header.h 文件中添加 #import <sqlite3.h>libsqlite3.dylib 在我的项目中实现了 Sqlite。

如何将数组作为参数传递给我的查询,这是我的想法:

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数据库,准备查询等等。

提前致谢。

您需要完成两件事:将您的 Int 数组转换为 String 数组,然后通过用逗号连接它们将数组内爆成一个字符串(正如您想要做的那样)使用 IN SQL 语句)。

这是一个基本功能,可以做到这一点:

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

然后在使用:

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

我可能会使用类似的东西:

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

您可以使用 join 函数轻松地将数组组合成一个字符串。

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

使用 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];

Swift3 更新:

var arrayId = [1,2] // array with interested Id
var inExpression = arrayId.flatMap{ String([=10=]) }.joined(separator: ",")
// inExpression = "1,2"
var query = "SELECT id FROM Product WHERE id IN (\(inExpression))"