iOS: 学习笔记, 使用FMDatabase操作sqlite3

使用FMDatabase操作sqlite3数据库非常简单和方便

 1 //
 2 //  main.m
 3 //  iOSDemo0602_sqlite3
 4 //
 5 //  Created by yao_yu on 14-6-2.
 6 //  Copyright (c) 2014年 yao_yu. All rights reserved.
 7 //
 8 
 9 #import <UIKit/UIKit.h>
10 #import "FMDatabase.h"
11 
12 void test01();
13 BOOL isfile(NSString *path);
14 BOOL isdir(NSString *path);
15 
16 int main(int argc, char * argv[])
17 {
18     @autoreleasepool {
19         test01();
20     }
21     return 0;
22 }
23 
24 void test01()
25 {
26     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
27     NSString *docpath = [paths objectAtIndex:0];
28     NSString *dbpath = [docpath stringByAppendingPathComponent:@"YY/Data2"];
29 //    NSLog(@"%@", dbpath);
30     if (!isdir(dbpath)) {
31         NSFileManager *fileManager = [NSFileManager defaultManager];
32         [fileManager createDirectoryAtPath:dbpath withIntermediateDirectories:YES attributes:nil error:nil];
33     }
34     
35     NSString *dbfile = [dbpath stringByAppendingPathComponent:@"data.db"];
36     NSLog(@"%@", dbfile);
37     
38     //初始化
39     FMDatabase *db = [FMDatabase databaseWithPath:dbfile];
40     //打开数据库
41     [db open];
42     
43     //删除表
44     [db executeUpdate:@"drop table persons"];
45     
46     //添加表
47     [db executeUpdate:@"create table persons(id, name)"];
48     
49     //删除原有数据
50     [db executeUpdate:@"delete from persons"];
51     
52     //使用事务添加数据
53     [db beginTransaction];
54     for(int i=0; i< 10000; i++)
55     {
56         [db executeUpdate:@"insert into persons values(?,?)", [NSString stringWithFormat:@"%d", i], [NSString stringWithFormat:@"第%d", i]];
57     }
58     [db commit];
59     
60     //数据查询
61     FMResultSet *cursor = [db executeQuery:@"select * from persons"];
62     int nCols = cursor.columnCount;
63     while ([cursor next]) {
64         for (int i=0; i<nCols; i++) {
65             printf("%s ", [[cursor stringForColumnIndex:i] UTF8String]);
66         }
67         printf("\n");
68     }
69     cursor = nil;
70     
71     //关闭数据库
72     [db close];
73     
74     //删除数据库测试文件
75     [[NSFileManager defaultManager] removeItemAtPath:dbfile error:nil];
76     
77 }
78 
79 BOOL isfile(NSString *path)
80 {
81     NSFileManager *fileManager = [NSFileManager defaultManager];
82     BOOL isdir = NO;
83     if ([fileManager fileExistsAtPath:path isDirectory: &isdir]) {
84         return isdir == NO;
85     }
86     return NO;
87 }
88 
89 BOOL isdir(NSString *path)
90 {
91     NSFileManager *fileManager = [NSFileManager defaultManager];
92     BOOL isdir = NO;
93     if ([fileManager fileExistsAtPath:path isDirectory: &isdir]) {
94         return isdir == YES;
95     }
96     return NO;
97 }

 

iOS: 学习笔记, 使用FMDatabase操作sqlite3,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。