· 7 years ago · Feb 27, 2019, 05:18 PM
1-(void)viewDidLoad
2{
3
4NSString *docsDir;
5NSArray *dirPaths;
6
7// Get the documents directory
8dirPaths = NSSearchPathForDirectoriesInDomains(
9 NSDocumentDirectory, NSUserDomainMask, YES);
10
11docsDir = [dirPaths objectAtIndex:0];
12
13// Build the path to the database file
14databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"todo.db"]];
15
16NSFileManager *filemgr = [NSFileManager defaultManager];
17
18if ([filemgr fileExistsAtPath: databasePath ] == NO)
19{
20 const char *dbpath = [databasePath UTF8String];
21
22 if (sqlite3_open(dbpath, &todoDB) == SQLITE_OK)
23 {
24 char *errMsg;
25 const char *sql_stmt = "CREATE TABLE IF NOT EXISTS TODO (ID INTEGER PRIMARY KEY AUTOINCREMENT, MYTASK TEXT, SUBTASK TEXT)";
26
27 if (sqlite3_exec(todoDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
28 {
29 status.text = @"Failed to create table";
30 }
31 status.text = @"Created the database";
32 sqlite3_close(todoDB);
33
34 } else {
35 status.text = @"Failed to open/create database";
36 }
37
38 } - (IBAction)save:(id)sender {
39
40[myTask resignFirstResponder];
41[subTask resignFirstResponder];
42
43
44sqlite3_stmt *statement;
45
46const char *dbpath = [databasePath UTF8String];
47
48if (sqlite3_open(dbpath, &todoDB) == SQLITE_OK)
49{
50
51 NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO TODO (MYTASK, SUBTASK) VALUES ("%@", "%@")", myTask.text, subTask.text];
52
53 const char *insert_stmt = [insertSQL UTF8String];
54
55 sqlite3_prepare_v2(todoDB, insert_stmt, -1, &statement, NULL);
56
57
58 if (sqlite3_step(statement) == SQLITE_DONE)
59
60 {
61 status.text = @"Contact added";
62
63 myTask.text = @"";
64
65 subTask.text = @"";
66
67 } else {
68
69
70 status.text = @"Failed to add contact";
71
72 }
73 NSLog(@"7");
74 sqlite3_finalize(statement);
75
76 sqlite3_close(todoDB);
77
78}
79
80-(void)viewDidLoad
81{
82const char *dbpath = [databasePath UTF8String];
83sqlite3_stmt *statement;
84
85NSLog(@"Display1");
86
87if (sqlite3_open(dbpath, &todoDB) == SQLITE_OK)
88{
89
90 NSLog(@"Display2");
91
92
93 NSString *querySQL = [NSString stringWithFormat:
94 @"SELECT MYTASK, SUBTASK FROM TODO "];
95
96 NSLog(@"Display3");
97
98
99 const char *query_stmt = [querySQL UTF8String];
100
101 NSLog(@"Display4");
102
103 if (sqlite3_prepare_v2(todoDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
104 {
105 NSLog(@"Display5");
106 if (sqlite3_step(statement) == SQLITE_ROW)
107 {
108 NSLog(@"Display6");
109
110
111 NSLog(@"Data is displayed");
112
113
114 } else {
115 NSLog(@"Display7");
116 NSLog(@"Data cannot be displayed");
117
118 }
119 sqlite3_finalize(statement);
120 }
121 sqlite3_close(todoDB);
122}