· 8 years ago · May 15, 2018, 12:56 PM
1[database executeUpdate:@"create table T_table(name text primary key, age int)"];
2
3create table test_table (test_no NUMBER, test_name TEXT); //Table created
4
5/* Now, try creating the table again */
6create table test_table (test_no NUMBER, test_name TEXT);
7
8create table if not exists test_table (test_no NUMBER, test_name TEXT);
9
10select sql from SQLITE_MASTER where name = 'test_table'
11
12var databasePath = String()
13 override func viewDidLoad() {
14 super.viewDidLoad()
15
16 let filemgr = FileManager.default
17 let dirPaths = filemgr.urls(for: .documentDirectory,
18 in: .userDomainMask)
19
20 databasePath = dirPaths[0].appendingPathComponent("contacts.db").path
21
22 if !filemgr.fileExists(atPath: databasePath as String) {
23
24 let contactDB = FMDatabase(path: databasePath as String)
25
26 if contactDB == nil {
27 print("Error: (contactDB.lastErrorMessage())")
28 }
29
30 if (contactDB.open()) {
31 let sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)"
32 if !(contactDB.executeStatements(sql_stmt)) {
33 print("Error: (contactDB.lastErrorMessage())")
34 }
35 contactDB.close()
36 } else {
37 print("Error: (contactDB.lastErrorMessage())")
38 }
39 }
40 save()
41
42 // Do any additional setup after loading the view, typically from a nib.
43 }
44
45 override func didReceiveMemoryWarning() {
46 super.didReceiveMemoryWarning()
47 // Dispose of any resources that can be recreated.
48 }
49 func save()
50 {
51 let contactDB = FMDatabase(path: databasePath as String)
52
53 if (contactDB.open()) {
54
55 let insertSQL = "INSERT INTO CONTACTS (name, address, phone) VALUES ('("abc")', '("abc")', '("1234")')"
56
57 let result = contactDB.executeUpdate(insertSQL,
58 withArgumentsIn: [])
59
60 if !result {
61 //status.text = "Failed to add contact"
62 print("Error: (contactDB.lastErrorMessage())")
63 }
64 else
65 {
66 getData()
67// status.text = "Contact Added"
68// name.text = ""
69// address.text = ""
70// phone.text = ""
71 }
72 } else {
73 print("Error: (contactDB.lastErrorMessage())")
74 }
75 }
76
77 func getData()
78 {
79 let contactDB = FMDatabase(path: databasePath as String)
80
81 if (contactDB.open()) {
82 // let querySQL = "SELECT address, phone FROM CONTACTS WHERE name = '(name.text!)'"
83 let querySQL = "SELECT ID,address, phone FROM CONTACTS"
84
85 let results:FMResultSet? = contactDB.executeQuery(querySQL,
86 withArgumentsIn: [])
87
88 while results?.next() == true
89 {
90 let id = results?.string(forColumn: "ID")
91 //(forColumn: "address")
92 let phone = results?.string(forColumn: "phone")
93 print(phone ?? "")
94 print("(id)")
95 //status.text = "Record Found"
96 }
97// else
98// {
99// print("")
100// // status.text = "Record not found"
101// // address.text = ""
102////phone.text = ""
103// }
104 contactDB.close()
105 }
106 else
107 {
108 print("Error: (contactDB.lastErrorMessage())")
109 }
110
111
112
113
114 }
115
116}