我正在使用SQLite Library并且在使用中它说let db = try Connection("path/to/db.sqlite3")
我有sqlite数据库位于文档中。但是当我尝试建立连接时会抛出错误call can throw but errors cannot be thrown out of a property initializer
这是我的代码:
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()
}
}
我也尝试在viewDidLoad中放置连接但仍然无法正常工作
出了什么问题?
答案 0 :(得分:1)
由于Connection
初始值设定项可以抛出异常,因此需要在do/catch
块中调用它。
所以你应该将声明改为:
var db : Connection?
并在ViewDidLoad
中初始化:
do{
self.db = try Connection("/Users/macbookpro/Documents/db.sqlite")
} catch {
print("Unable to create connection: \(error)")
}
答案 1 :(得分: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
}
}
以这种方式调用数据库实例
try DBModelManager.getInstance().database!.prepare()