I have created a database in one view controller and I would like to open it and access it in another view controller. I was wondering how to open up a existing database from one view controller in another view controller. I intend to open up the database and be able to update a row, so I would also need access to the "parts" (ex. id, name, email). Could you help me? Anything would be helpful. Thanks!
Asked
Active
Viewed 141 times
1 Answers
0
You can access your DB from any VC. Code (which you will probably use anywhere you want to access your DB from) would be like
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
do {
let db = try Connection("\(path)/<your.db.filename>")
let recordsTable = Table("records")
//or whatever you'd like to do, extract, modify, insert or delete
}
catch let error {
print("Data operation failed for records table: \(error)")
}
Instead of copying same code all over your project, you can separately create your own class for any of your DB operations and access it from anywhere:
class DatabaseOps {
//..
func getHighscoreTable() -> Array<HighScoreDataArray> {
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
var highscores = [HighScoreDataArray]()
do {
let db = try Connection("\(path)/tasksolver.db")
let score = Expression<Int>("Score")
let username = Expression<String>("Username")
let recordsTable = Table("records").order(score.desc).limit(10)
for row in try db.prepare(recordsTable) {
let highscore = HighScoreDataArray(score: Int(row[score]), username: String(row[username]))
highscores += [highscore]
}
} catch let error {
print("Data operation failed for records table: \(error)")
}
return highscores
}
//..
}
class RecordsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var myDb : DatabaseOps = DatabaseOps()
//...
super.viewDidLoad()
//get the data from database by using myDB method
myHighScoreTable = myDb.getHighscoreTable()
Also, before you try it in different VCs - don't forget to make sure you have your DB file in place. If it is not, let db = try Connection will create an empty database for you, which will not contain any of your data or tables you want to access.

Andrey Lesnykh
- 84
- 5