1 #import "UserDB.h"
2 #import <FMDB.h>
3
4 #define dataBasePath [[(NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)) lastObject]stringByAppendingPathComponent:dataBaseName]
5 #define dataBaseName @"GuoBIn.sqlite"
6
7 // 把userDB设计成一个单例类
8 static UserDB *instnce;
9
10 @implementation UserDB
11
12 // 把userDB设计成一个单例类
13 + (id)shareInstance
14 {
15 if (instnce == nil) {
16 instnce = [[[self class] alloc] init];
17 }
18 return instnce;
19 }
20
21 // 创建用户表
22 - (void)createTable
23 {
24 // 文件路径
25 NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",dataBaseName];
26 NSLog(@"文件路径 == %@",filePath);
27
28 FMDatabase *db = [FMDatabase databaseWithPath:dataBasePath];
29
30 if ([db open]) {
31 if (![db tableExists:@"user"]) {
32 if ([db executeUpdate:@"CREATE TABLE user (Serial text primary key,dataText text)"]) {
33 NSLog(@"创建表成功");
34 }else{
35 NSLog(@"创建表失败");
36 }
37 } else {
38 NSLog(@"表已经存在");
39 }
40 } else{
41 NSLog(@"打开表失败");
42 }
43 [db close];
44
45 }
46
47 // 添加用户
48 - (void)addData:(NSArray *)dataArray
49 {
50 NSString *serial = [dataArray objectAtIndex:0];
51 NSString *dataText = [dataArray objectAtIndex:1];
52
53 FMDatabase *db = [FMDatabase databaseWithPath:dataBasePath];
54 if ([db open]) {
55 // 插入数据
56 [db executeUpdate:@"insert into user (Serial,DataText) values(?,?)",serial,dataText,nil];
57 }
58 [db close];
59 }
60
61 // 查询用户
62 - (NSArray *)findDatas
63 {
64 NSMutableArray *users = [NSMutableArray array];
65 FMDatabase *db = [FMDatabase databaseWithPath:dataBasePath];
66 if ([db open]) {
67 // 获取所有数据
68 FMResultSet *rs = [db executeQuery:@"SELECT * FROM user"];
69 while ([rs next]) {
70 NSString *serial = [rs stringForColumn:@"Serial"];
71 NSString *dataText = [rs stringForColumn:@"DataText"];
72
73 [users addObject:@[serial,dataText]];
74 }
75 [rs close];
76 }
77 [db close];
78 return users;
79 }
80
81 - (void)deleteRowData:(NSArray *)array
82 {
83 NSString *serial = [array objectAtIndex:0];
84 NSString *dataText = [array objectAtIndex:1];
85
86 FMDatabase *db = [FMDatabase databaseWithPath:dataBasePath];
87 if ([db open]) {
88 // 删除某个数据
89 BOOL rs = [db executeUpdate:@"DELETE FROM user WHERE Serial = ? and DataText = ?",serial,dataText];
90
91 if (rs) {
92 NSLog(@"删除成功");
93 } else {
94 NSLog(@"删除失败");
95 }
96 }
97 [db close];
98 }
99
100 // 清空表中的数据:
101 - (void)clearTableData
102 {
103 FMDatabase *db = [FMDatabase databaseWithPath:dataBasePath];
104 if ([db open]) {
105 // 清除全部数据
106 [db executeUpdate:@"DELETE FROM user"];
107 }
108 [db close];
109 }
110
111 // 更新数据
112 - (void)executeUpdate:(NSArray *)array
113 {
114 NSString *serial = [array objectAtIndex:0];
115 NSString *dataText = [array objectAtIndex:1];
116
117 FMDatabase *db = [FMDatabase databaseWithPath:dataBasePath];
118 if ([db open]) {
119 [db executeUpdate:@"UPDATE user SET DataText = ? WHERE Serial = ?",dataText,serial];
120 }
121 [db close];
122
123 }
124
125 @end