Reputation: 988
Problem
I wanna use SQLite.swift framework on my project to access my local preloaded (read-only) database file (db.sqlite3) which located in my current project directory. I created my db connection as let db = try? Connection("path/to/db.sqlite3")
First question is when I keep my db in my project directory can I involve connection path as Connection("path/to/db.sqlite3")
or Connection("db.sqlite3")
? (What's the meaning of path/to of course, I'm wondering) Anyway, my main question is how can I query my local db? What's wrong?
Here is my code but it doesn't work. This code mostly similar to SQLite.swift's github documantion page but it doesn't work in Swift 2.2
override func viewDidLoad() {
super.viewDidLoad()
let db = try? Connection("path/to/db.sqlite3")
let users = Table("users")
for user in try! db!.prepare(users) {
print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
// id: 1, name: Optional("Alice"), email: [email protected]
}
// Do any additional setup after loading the view.
}
I have already copied my db files to Copy Bundle Resources (Build Phrase)
My working directory
Note: I tried db connection as "path/to/db.sqlite3" and "db.sqlite3". So, this is not the solution.
Upvotes: 0
Views: 1492
Reputation: 988
Updated for Swift 3+
I read the documantation carefully again and found the answer like this:
let path = Bundle.main.path(forResource: "db", ofType: "sqlite3")!
let db = try? Connection(path, readonly: true)
for row in try! db!.prepare("SELECT id, email FROM users") {
print("\(row[0]!), \(row[1]!)")
}
Upvotes: 3
Reputation: 4379
Converted in Swift 3.0
let path = Bundle.main.path(forResource: "SMP", ofType: "sqlite")!
let db = try? Connection(path)
// Insert Rows ======
let stmt = try! db!.prepare("INSERT INTO tbl_workout (name) VALUES (?)")
for name in ["Workout1", "Workout2"] {
try! stmt.run(name)
}
// Fetch Rows ======
for row in try! db!.prepare("SELECT * FROM tbl_workout") {
print("id: \(String(describing: row[0])), email: \(String(describing: row[1]))")
}
Upvotes: 0