I know there are some resources available for this but none of them clearly show the way how to do it properly.
I have already populated .sqlite database (MTrader.db) and i want to connect it to my swift project and load the data from the database into spinner.
I tried so many ways but it doesn't work. I try to edit lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? method in AppDelegete.swift as
if !NSFileManager.defaultManager().fileExistsAtPath(url.path!) {
let sourceSqliteURLs = [NSBundle.mainBundle().URLForResource("MTrader", withExtension: "db")!]
let destSqliteURLs = [self.applicationDocumentsDirectory.URLByAppendingPathComponent("MTrader.db")]
var error:NSError? = nil
for var index = 0; index < sourceSqliteURLs.count; index++ {
NSFileManager.defaultManager().copyItemAtURL(sourceSqliteURLs[index], toURL: destSqliteURLs[index], error: &error)
}
}
For some reason above code isn't working. I copied my database file in my project. So is there any error with my code or any better way to use my existing database without creating new database and populating it?
答案 0 :(得分:6)
First add libsqlite3.dylib to your Xcode project (in project settings/Build Phases/Link Binary with Libraries), then use something like fmdb, it makes dealing with SQLite a lot easier. It's written in Objective-C but can be used in a Swift project, too.
Then you could write a DatabaseManager
class, for example...
import Foundation;
class DatabaseManager {
private let dbFileName = "database.db"
private var database:FMDatabase!
init() {
openDatabase()
}
func openDatabase() {
let resourcePath = NSBundle.mainBundle().resourceURL!.absoluteString
let dbPath = resourcePath?.stringByAppendingPathComponent(dbFileName)
let database = FMDatabase(path: dbPath)
/* Open database read-only. */
if (!database.openWithFlags(1)) {
println("Could not open database at \(dbPath).")
} else {
self.database = database;
}
}
func closeDatabase() {
if (database != nil) {
database.close()
}
}
func query(queryString:String) {
if let db = database, q = db.executeQuery(queryString, withArgumentsInArray: nil) {
while q.next() {
let data = q.stringForColumn("columnName")
// Do whatever here with fetched data, usually add it to an array and return that array
}
}
}
}
答案 1 :(得分:3)
I have already populated .sqlite database
So you probably populated it using sqlite.
I try to edit
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator?
But there's your problem. NSPersistentStoreCoordinate is about Core Data, not sqlite. Core Data can use a sqlite backing store, but it can't open an arbitrary sqlite database file; you're not going to be able to use a sqlite database created independently, using sqlite, with Core Data. Use sqlite itself! The easiest way is with fmdb.