· 8 years ago · Dec 24, 2017, 04:24 PM
1import UIKit
2import SQLite3
3
4class ViewController: UIViewController {
5
6 var db: OpaquePointer?
7 var gstudentcount: Int = 0
8 var queryCount: Int = 0
9 var id: Int = 0
10 var name: String = ""
11 var grade: Int = 0
12
13override func viewDidLoad() {
14 super.viewDidLoad()
15 openDatabase()
16 createStudentsTable()
17 getRecordsCount()
18 let gstudentcount = getRecordsCount()
19
20 if gstudentcount == 0 {
21
22 performSegue(withIdentifier: "registerVC", sender: self)
23
24 }
25
26 func openDatabase()
27 {
28
29 let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
30 .appendingPathComponent("database.sqlite")
31
32 if sqlite3_open(fileURL.path, &db) == SQLITE_OK {
33 print("Database Created !!")
34 }
35
36 }
37
38 func createStudentsTable()
39 {
40 if sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS Students (id INTEGER PRIMARY KEY AUTOINCREMENT, StudentName TEXT, Grade INTEGER)", nil, nil, nil) != SQLITE_OK
41 {
42 let errmsg = String(cString: sqlite3_errmsg(db)!)
43 print("error creating table: (errmsg)")
44 } else
45 {
46 print("Database Table created")
47 }
48
49 }
50
51 func getRecordsCount() -> Int32
52 {
53 //this is our select query
54 let countQuery = "SELECT count(*) FROM Students"
55
56 //statement pointer
57 var qstmt:OpaquePointer?
58
59 if sqlite3_prepare(db, countQuery, -1, &qstmt, nil) == SQLITE_OK
60 {
61
62 if (sqlite3_step(qstmt) == SQLITE_ROW)
63
64 {
65 let id = sqlite3_column_int(qstmt, 0)
66 print ("printing students count from main view controller (id)")
67 return id
68 } else
69 {
70 return 99
71 }
72
73 } else
74 {
75 print ("Query did not execute properly")
76 return 99
77 }
78
79 }
80
81import UIKit
82import SQLite3
83
84
85class RegisterViewController: UIViewController {
86
87 override func viewDidLoad() {
88 super.viewDidLoad()
89
90
91 let rstudentsCount = ViewController().getRecordsCount()
92 print("this is from RegisterViewController: (rstudentsCount)")
93
94
95 // Do any additional setup after loading the view.
96 }