0

i'm using SQLite Library and in usage it says let db = try Connection("path/to/db.sqlite3") i have sqlite database located in documents. but when i try to make connection it throw an error call can throw but errors cannot be thrown out of a property initializer

here's my code :

import UIKit
import SQLite

class SearchViewController: UIViewController, UITextFieldDelegate {

let db = try Connection("/Users/macbookpro/Documents/db.sqlite") //error
let categoryVC = CategoryViewController()
let UseFullVC = UseFullViewController()
let MapVC = MapViewController()
let EventVC = SearchResultOnlineVC()

@IBOutlet weak var searchTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Search"

    searchTextField.delegate = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

i also try to put connection in viewDidLoad but still doesn't work

what's wrong?

1
  • why cant you go with the FMDB, why using raw sqlite ? Commented Jan 27, 2017 at 9:23

2 Answers 2

1

Since the Connection initializer can throw an exception, you need to call it in a do/catch block.

So you should change the declaration to:

var db : Connection?

And initialize it in ViewDidLoad:

do{
    self.db = try Connection("/Users/macbookpro/Documents/db.sqlite")
} catch {
    print("Unable to create connection: \(error)")
}
Sign up to request clarification or add additional context in comments.

Comments

0
import UIKit
import SQLite

let sharedInstance = DBModelManager()

class DBModelManager: NSObject {
  var database: Connection!

 class func getInstance() -> DBModelManager
 {
     if(sharedInstance.database == nil)
     {
         do{
             let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
             let fileUrl = documentDirectory.appendingPathComponent("dbname").appendingPathExtension("sqlite3")
             sharedInstance.database = try Connection(fileUrl.path)

         }catch{
             print("DB Error \(error)")
         }
     }
     return sharedInstance
  }
}

Call DB instance this way

try DBModelManager.getInstance().database!.prepare()

Comments

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.