0

I use SQLite.swift and want to replace the question marks in a statement. This can be done for single entries like this:

let stmt = db.prepare("INSERT INTO users (email) VALUES (?)")
for email in ["[email protected]", "[email protected]"] {
    stmt.run(email)
}

I did not see how I can do the following to use a array like:

var values:[String] = ["test1","test2", "test3"]

in a Statement like:

let stmt = db.prepare("SELECT * from users where email in (?)")

The following does not work:

stmt.run(values)

How do I use an NSArray as an argument for a statement?

3
  • how about for email in values { stmt.run(email) } Sorry if I misinterpret your question.... Commented Apr 16, 2015 at 15:18
  • @deanware Won't this generate one query for each Array entry? Commented Apr 16, 2015 at 15:19
  • ahh yes...your right...this is not what your looking for....sorry... Commented Apr 16, 2015 at 15:23

1 Answer 1

1

If you're using the type-safe layer, you can use contains():

users.filter(contains(["test1", "test2"], email))

// the above assumes this boilerplate precedes it:
let email = Expression<String>("email")
let users = db["users"]

If you're using the raw SQLite3 API, it does not support arrays, so you'll need to format those yourself:

let emails = ["test1", "test2"]
let template = join(", ", [String](count: count(emails), repeatedValue: "?"))
let stmt = db.prepare(
    "SELECT * FROM users WHERE email IN (\(template))", emails
)
Sign up to request clarification or add additional context in comments.

2 Comments

Why is the last , emails ? What does this mean?
It's defined immediately above it. template basically expands the number of emails to the number of needed ?s, in this case ?, ?. This basically makes the following: db.prepare("SELECT * FROM users WHERE email IN (?, ?)", ["test1", "test2"])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.