数据库管理

数据库类型
NULL nil
INTEGER 有符号整数
TEXT 文本字符串,支持编码格式(UTF-8,UTF-16BE或UTF-16LE)
REAL real 浮点值

{
    sqlite3 * _db;//数据库管理手柄
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self open];
    [self create];
    [self insert];
//   [self delete];
    [self quarry];
    
}

打开数据库

-(void)open{
    //路径

    NSString *nsPath= [NSString stringWithFormat:@"%@/Documents/person,db",NSHomeDirectory()];
    
    char *path = [nsPath UTF8String];
    //打开数据库
    
    int ret = sqlite3_open(path, &_db);
    if(ret == SQLITE_OK){
        NSLog(@"数据库打开成功");
        
    }else{
        NSLog(@"数据库打开失败");
        
    }
 
}

创建表格

-(void)create{
    //sqlite语句格式:创建表格-Creae table if not exists 表格名字英文可以用下划线链接(字段 字段类型,字段1 字段1类型 以此类推)分号结尾
    const char *sql = "CREATE TABLE IF NOT EXISTS T_Student (id integer PRIMARY KEY AUTOINCREMENT,name text,score real DEFAULT 0,sex text DEFAULT '不明确');";
    int result = sqlite3_exec(_db, sql, NULL, NULL, NULL);
    if(result == SQLITE_OK){
        
         NSLog(@"创建表格成功");
        
    }else{
        
         NSLog(@"创建表格失败");
        
    }
}

插入信息

-(void)insert{
    const char *sql = "INSERT INTO t_Student(name,score,sex) VALUES('Lucy',45,'女');";
    int result = sqlite3_exec(_db, sql, NULL, NULL, NULL);
    if(result == SQLITE_OK){
        NSLog(@"数据插入成功");
    }else{
        NSLog(@"数据插入失败");
    }
}

-(void)delete{
    const char *sql = "DELETE FROM t_Student WHERE score < 50;";
    //增删改都用它
    int result = sqlite3_exec(_db, sql, NULL, NULL, NULL);
    if(result == SQLITE_OK){
        NSLog(@"数据删除成功");
    }else{
        NSLog(@"数据删除失败");
    }
    
}

查询

-(void)quarry{
    const char *sql = " SELECT name,score FROM t_Student;";
    sqlite3_stmt *stmt;
    //第三个参数  需要穿sql语句的长度   -1表示自动计算
    int  result = sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL);
    if(result == SQLITE_OK){
        NSLog(@"查询成功");
        while (sqlite3_step(stmt)== SQLITE_ROW) {const unsigned char *name =sqlite3_column_text(stmt, 0);
            double score = sqlite3_column_double(stmt, 1);
            NSLog(@"姓名:%s 分数%.2lf",name,score);
            
        }
    }else{
        NSLog(@"查询失败");
    }

关闭数据

    int closeResult =  sqlite3_close_v2(_db);
    NSLog(@"closeResult:%d",closeResult);
    if (closeResult == SQLITE_OK){
        NSLog(@"数据库关闭成功");
    }else{
        NSLog(@"数据库关闭失败");
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容