SQLite

SQLite (http://www.sqlite.org/docs.html) 是一个轻量级的关系数据库。SQLite最初的设计目标是用于嵌入式系统,它占用资源非常少,在嵌入式设备中,只需要几百K的内存就够了,目前应用于Android、iOS、Windows Phone等智能手机。iOS 使用时SQLite,只需要加入 libsqlite3.dylib 依赖以及引入 sqlite3.h 头文件即可。
数据库操作包含打开数据库、创建表,表的增、删、改、查。下面代码给出了数据库操作。
创建并打开数据库:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSString *docsDir;
    NSArray *dirPaths;
    //获取数据库文件路径
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];

    databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"info.db"]];

    NSFileManager *filemanager = [NSFileManager defaultManager];

    if ([filemanager fileExistsAtPath:databasePath] == NO) {
        const char *dbpath = [databasePath UTF8String];
        if (sqlite3_open(dbpath, &dataBase)==SQLITE_OK) {
            char *errmsg;
            const char *createsql = "CREATE TABLE IF NOT EXISTS INFO (ID INTEGER PRIMARY KEY AUTOINCREMENT, NUM TEXT, CLASSNAME TEXT,NAME TEXT)";
            if (sqlite3_exec(dataBase, createsql, NULL, NULL, &errmsg)!=SQLITE_OK) {
                status.text = @"create table failed.";
            }
        }
        else {
            status.text = @"create/open failed.";
        }
    }
}

iOS中没有提供创建数据库的命令,当使用sqlite3_open时,如果数据库文件不存在会自行创建数据库,如果存在会打开数据库。打开数据库后就可以创建表并操作表内容了,iOS中的sqlite3使用sqlite3_exec来创建表、插入表内容、修改表内容、删除表内容等操作,使用sqlite3_prepare_v2来查询表。下面给给出了sqlite3_exec的封装:

 -(void)execSql:(NSString *)sql  
{      
    if ([self openDB]) {  
        char *err;  
        if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {  
            NSLog(@"数据库操作数据失败!");  
        }else{  
            NSLog(@"%@",sql);  
        }  
        sqlite3_close(db);  
    }      
}  

创建表:

NSString *sqlCreateTable =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT, '%@' INTEGER, '%@' TEXT)",TABLENAME,ID,NAME,AGE,ADDRESS]; [self execSql:sqlCreateTable]; 

插入数据

        -(void) insertData{  
    NSString *insertSql1= [NSString stringWithFormat:  
                      @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')", TABLENAME, NAME, AGE, ADDRESS, @"张三", @"13", @"济南"]; [self execSql:insertSql1]; NSString *insertSql2 = [NSString stringWithFormat: @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')", TABLENAME, NAME, AGE, ADDRESS, @"李四", @"12", @"济南"]; [self execSql:insertSql2]; } 

修改表:

-(void) updateData{  
    NSString *updateSql = [NSString stringWithFormat:  
    @"UPDATE '%@' SET '%@' = '%@' WHERE '%@' = '%@'", TABLENAME, AGE, @"15" ,AGE, @"13"]; [self execSql:updateSql]; } 
 删除表内容:
-(void) deleteData{  
    NSString *sdeleteSql = [NSString stringWithFormat:  
                      @"delete from %@ where %@ = '%@'",  
                      TABLENAME, NAME, @"张三"];  
    [self execSql:sdeleteSql];  
}  

上面实现了表内容的增、改、删,下面实现表内容查询。

-(void) selectData{  

    [self openDB];  
    NSString *sqlQuery = [NSString stringWithFormat:  
                      @"SELECT * FROM %@",TABLENAME];  
    sqlite3_stmt * statement;  

    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {  

        //查询结果集中一条一条的遍历所有的记录,这里的数字对应的是列值,注意这里的列值 

        while (sqlite3_step(statement) == SQLITE_ROW) {  
            char *name = (char*)sqlite3_column_text(statement, 1);  
            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];  

            int age = sqlite3_column_int(statement, 2);  

            char *address = (char*)sqlite3_column_text(statement, 3);  
            NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];  

            NSLog(@"name:%@ age:%d address:%@",nsNameStr,age, nsAddressStr);  
        }  
    }else{  
        NSLog(@"select error:%@",sqlQuery);  

    }  
    sqlite3_close(db);  
}  

你可能感兴趣的:(ios)