I'm working a project where I need to use a SQLite database to read, create , and edit different objects. I thought I had established the connection properly but, it turns out I had only established a read only connection. How do I modify this code to be a read-write connection using 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
}
}
Edit there's a func copyDatabaseIfNeeded in the documentation so maybe my true question is in what context do I use this func to copy the database to the application support directory?
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
}
}