1

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

1
  • Could you please give tutorials link to get started with swlite3 in ios swift? Commented Jan 29, 2018 at 10:32

1 Answer 1

1

First of all, I would recommend that you put all the database related code into a standalone class and not a UIViewController. Generally it's good practice to separate out concerns so that your view controller does not become a Massive View Controller (with tons of code not central to the main job of the view controller).

The error is a result of calling getRecordsCount without first opening the database.

Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the feedback. I did exactly as you said and it works like a charm !!. Thanks a bunch.
@iosappdevguy Glad to hear it! Can you please accept my answer? "To mark an answer as accepted, click on the check mark beside the answer to toggle it from greyed out to filled in."
new to stack overflow :)..getting my basics here too...done.
@MobileWarrior Could you please give tutorials link to get started with swlite3 in ios swift?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.