我正在做一個專案,我需要使用 SQLite 資料庫來讀取、創建和編輯不同的物件。我以為我已經正確建立了連接,但事實證明我只建立了一個只讀連接。如何使用 SQLite.swift 將此代碼修改為讀寫連接
import Foundation
import SQLite
import UIKit
let path = Bundle.main.path(forResource: "Assignment2", ofType: "sqlite3")
//Array of customer structs to populate the table
var customerArray: [Customer] = []
class CustomerPageVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
//IBOutlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var addCustButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//Additional Setup
do {
//Search for DB in documents directory
let db = try Connection(path!)
let customers = Table("Customers")
//Define the columns of the table as expressions
let id = Expression<Int64>("CustomerID")
let name = Expression<String>("CustomerName")
let contactName = Expression<String>("ContactName")
let address = Expression<String>("Address")
let city = Expression<String>("City")
let postalCode = Expression<String>("PostalCode")
let country = Expression<String>("Country")
//Load the data from db file into customerArray
for customer in try db.prepare(customers) {
let cust = Customer(Int(customer[id]), customer[name], customer[contactName], customer[address], customer[city], customer[postalCode], customer[country])
customerArray.append(cust)
}
}
catch {
print(error)
}
tableView.delegate = self
tableView.dataSource = self
}
}
編輯檔案中有一個 func copyDatabaseIfNeeded 所以也許我真正的問題是在什么情況下我使用這個 func 將資料庫復制到應用程式支持目錄?
func copyDatabaseIfNeeded(sourcePath: String) -> Bool {
let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let destinationPath = documents "/db.sqlite3"
let exists = FileManager.default.fileExists(atPath: destinationPath)
guard !exists else { return false }
do {
try FileManager.default.copyItem(atPath: sourcePath, toPath: destinationPath)
return true
} catch {
print("error during file copy: \(error)")
return false
}
}
您可以在此處找到 SQLite.swift 的檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/431229.html
標籤:IOS 迅速 sqlite sqlite.swift
