建立一個sms.db數據庫倆面在建立一個message表,插入數據而後在讀取數據

FMDB第三方庫
sql

導入頭文件數據庫

#import "FMDatabase.h"
#import "FMResultSet.h"ui

FMDatabase *_database;//數據庫對象code

- (void)readData{
    //1.獲取數據庫文件的路徑
    NSArray *path=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
   NSString *documentPath=[path objectAtIndex:0];
   NSString *dbPath=[documentPath stringByAppendingPathComponent:@"sms.db"];
    //2.建立database
    _database=[[FMDatabase alloc]initWithPath:dbPath];
    //3.open
//第一次 數據庫文件若是不存在那麼 會建立而且打開
        //若是存在 那麼直接打開
    if ([_database open]) {
        NSLog(@"數據庫打開成功");
        //建立新表不存在的話,
        NSString *sql=@"create table if not exists message(serial integer Primary Key Autoincrement,guid integer,text string)";
        //除了查詢其餘一切都用executeUpdate
        BOOL isSuccess=[_database executeUpdate:sql];
        if (!isSuccess) {
            NSLog(@"creatTable error:%@",_database.lastErrorMessage);
           
        }
        //插入數據
        NSString *sql2=@"insert into message (serial,guid,text) values(?,?,?)";
        BOOL isSuccess2=[_database executeUpdate:sql2,@"111",@"119",@"111"];
        if (!isSuccess2) {
            NSLog(@"插入失敗");
        }else{
            NSLog(@"插入成功");
        }

    }
    //查找表AllTheQustions
    FMResultSet *resultSet=[_database executeQuery:@"select * from message"];
    //逐行讀取數據
    while ([resultSet next]) {
        //對應字段來讀取數據
        NSString *serial=[resultSet stringForColumn:@"serial"];
        NSString *guid=[resultSet stringForColumn:@"guid"];
        NSString *text=[resultSet stringForColumn:@"text"];
        NSLog(@"serial:%@guid:%@,text:%@",serial,guid,text);
    }
    [_database close];
}
相關文章
相關標籤/搜索