I am new to swift programming. I am trying to build an app that is heavy on data so I decided to use Sqlite to store the data. I succeeded in creating the database, create table, insert data and access data in the main ViewController which is "ViewController.swift". I then added a second view Controller and its own "RegisterViewController.swift". When I tried to access regular function from my first view controller in second it worked fine. BUT..Here it comes....when I tried to access database functions, it gives me following error....I tried all options of closing DB in my first View controller and reopening in second view controller....nothing seems to work...I need some expert help here.
I am testing this on xCode9.1 and Swift 4
import UIKit
import SQLite3
class ViewController: UIViewController {
var db: OpaquePointer?
var gstudentcount: Int = 0
var queryCount: Int = 0
var id: Int = 0
var name: String = ""
var grade: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
openDatabase()
createStudentsTable()
getRecordsCount()
let gstudentcount = getRecordsCount()
if gstudentcount == 0 {
performSegue(withIdentifier: "registerVC", sender: self)
}
func openDatabase()
{
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("database.sqlite")
if sqlite3_open(fileURL.path, &db) == SQLITE_OK {
print("Database Created !!")
}
}
func createStudentsTable()
{
if sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS Students (id INTEGER PRIMARY KEY AUTOINCREMENT, StudentName TEXT, Grade INTEGER)", nil, nil, nil) != SQLITE_OK
{
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error creating table: \(errmsg)")
} else
{
print("Database Table created")
}
}
func getRecordsCount() -> Int32
{
//this is our select query
let countQuery = "SELECT count(*) FROM Students"
//statement pointer
var qstmt:OpaquePointer?
if sqlite3_prepare(db, countQuery, -1, &qstmt, nil) == SQLITE_OK
{
if (sqlite3_step(qstmt) == SQLITE_ROW)
{
let id = sqlite3_column_int(qstmt, 0)
print ("printing students count from main view controller \(id)")
return id
} else
{
return 99
}
} else
{
print ("Query did not execute properly")
return 99
}
}
Here is my second view controller code.
import UIKit
import SQLite3
class RegisterViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let rstudentsCount = ViewController().getRecordsCount()
print("this is from RegisterViewController: \(rstudentsCount)")
// Do any additional setup after loading the view.
}
Error Messages from RegisterViewController: API call with NULL database connection pointer
misuse at line 123195 of [2b0954060f]
Query did not execute properly