OC中数据库的基本使用

简单介绍一下OC中数据库的使用,内容有数据库的创建、表的创建、列的创建和基本的增删改查,首先要知道,数据库语法不区分大小写。
新建一个类DataBase,继承与NSObject
首先使用前需要导入库:

 #import

这个库需要在工程中->targets->General->Linked Frameworks and Libraries中添加libsqlite3.tbd后才能正常使用
先说.h文件
创建一个全局的sqlite对象,在该类中对数据库的操作都需要利用它来完成。

@interface DataBase : NSObject
{
sqlite3 *sqlite; //创建全局sqlite对象
}

然后是其他的方法

//获取实例
+ (DataBase *)defaultDB;
//打开数据库
- (BOOL)openDB:(NSString *)sqlName;
//关闭数据库
- (BOOL)closeDB;
//创建表
- (BOOL)createTable:(NSString *)tableName;
//创建列
- (BOOL)createColumn:(NSString *)column tableName:(NSString *)tableName;
//增加数据
- (BOOL)insertSQLWithColumnName:(NSString *)columnName columnValue:(NSString *)columnValue tableName:(NSString *)tableName;
//删除数据
- (BOOL)deleteSQLWithWhereStr:(NSString *)whereStr tableName:(NSString *)tableName;
//更改数据
- (BOOL)updateSQLWithNewColumnsKeyAndValue:(NSString *)newColumnsKeyAndValue whereStr:(NSString *)whereStr tableName:(NSString *)tableName;
//查找数据
- (sqlite3_stmt *)selectSQLWithOrderBy:(NSString *)orderBy findStr:(NSString *)findStr whereStr:(NSString *)whereStr limit:(int)limit tableName:(NSString *)tableName;

现在说.m文件

#import "DataBase.h"
static DataBase *db;    //全局静态实例变量
@implementation DataBase
//获取实例
+ (DataBase *)defaultDB
{
if (!db)
{
db = [[DataBase alloc]init];
}

刚刚创建了一个全局的sqlite对象,大家应该知道,OC里面无法在类方法中使用属性对象或者全局变量,要使用必须在实例方法中,所以这里创建全局静态实例变量,实例化之后再调用数据库操作所需方法,类似于单例的效果

//打开数据库
- (BOOL)openDB:(NSString *)sqlName
{
//获取本地数据库保存路径
NSString *sqlPath = @"数据库的保存路径,自己写";
int result = sqlite3_open([sqlPath UTF8String], &sqlite);
if (result == SQLITE_OK) {
return YES;    //获取成功返回YES,不过测试发现,如果该路径下没有数据库文件则会自动创建一个数据库
}

return NO;
}
//关闭数据库
- (BOOL)closeDB
{
int result = sqlite3_close(sqlite);
if (result == SQLITE_OK) {
return YES;
}
return NO;
}
//创建表语法:   CREATE TABLE 表名 (列名),
- (BOOL)createTable:(NSString *)tableName
{
    char *err;
    
    NSString *sql;
    
    sql = [NSString stringWithFormat:@"create table %@(page,type,message,create_time)",tableName];

    NSLog(@"[Create SQL] : %@",sql);
    
    int result = sqlite3_exec(sqlite, [sql UTF8String], NULL, NULL, &err);
    
    if (result == SQLITE_OK) {
        NSLog(@"[Create SQL] : %@",sql);
        return YES;
    }else {
        NSLog(@"[Create SQL] : Fail");
        NSLog(@"error = %s",err);
    }
    
    return NO;
}
//创建列语法:   alter table tableName(表名) add columnName(列名)
- (BOOL)createColumn:(NSString *)column tableName:(NSString *)tableName
{
    char *err;
    
    NSString *sql = [NSString stringWithFormat:@"alter table %@ add %@",tableName,column];
    NSLog(@"[Create SQL] : %@",sql);
    
    int result = sqlite3_exec(sqlite, [sql UTF8String], NULL, NULL, &err);
    
    if (result == SQLITE_OK) {
        NSLog(@"[Create SQL] : OK");
        return YES;
    }else {
        NSLog(@"[Create SQL] : Fail");
        NSLog(@"error = %s",err);
    }
    
    return NO;
}
//增加数据语法 insert into 表名 (列) values(值)   ,这里要注意的是,值必须用 '' 包含,如 values('page','type','message','createtime'),方法里面没写是因为调用时传入的string已经写好
- (BOOL)insertSQLWithColumnName:(NSString *)columnName columnValue:(NSString *)columnValue tableName:(NSString *)tableName
{
    char *err;
    
    NSString *sql = [NSString stringWithFormat:@"insert into %@(%@) values(%@)",tableName,columnName,columnValue];
    NSLog(@"[Insert SQL] : %@",sql);
    
    int result = sqlite3_exec(sqlite, [sql UTF8String], NULL, NULL, &err);
    if (result == SQLITE_OK) {
        NSLog(@"[DB Insert] : OK");
        return YES;
    }else {
        NSLog(@"[DB Insert] : Fail");
        NSLog(@"error = %s",err);
    }
    
    return NO;
}
//删除数据语法: delete from 表名 where 条件,条件写法为 列='值',如 page='1',或者page='1' and message='内容'。当然条件写法有很多种,这里只是介绍其中一种。
- (BOOL)deleteSQLWithWhereStr:(NSString *)whereStr tableName:(NSString *)tableName
{
    char *err;
    
    NSString *sql = [NSString stringWithFormat:@"delete from %@ where %@",tableName,whereStr];
    NSLog(@"[Delete SQL] : %@",sql);
    
    int result = sqlite3_exec(sqlite, [sql UTF8String], NULL, NULL, &err);
    if (result == SQLITE_OK) {
        NSLog(@"[DB Delete] : OK");
        return YES;
    }else {
        NSLog(@"[DB Delete] : Fail");
        NSLog(@"error = %s",err);
    }
    
    return NO;
}
//更改数据语法:update 表名 set 新数据 where 旧数据,这里的写法也有很多,如 set page='1' where page='2'
- (BOOL)updateSQLWithNewColumnsKeyAndValue:(NSString *)newColumnsKeyAndValue whereStr:(NSString *)whereStr tableName:(NSString *)tableName
{
    char *err;
    
    NSString *sql = [NSString stringWithFormat:@"update %@ set %@ where %@",tableName,newColumnsKeyAndValue,whereStr];
    NSLog(@"[Update SQL] : %@",sql);
    
    int result = sqlite3_exec(sqlite, [sql UTF8String], NULL, NULL, &err);
    if (result == SQLITE_OK) {
        NSLog(@"[DB Update] : OK");
        return YES;
    }else {
        NSLog(@"[DB Update] : Fail");
        NSLog(@"error = %s",err);
    }
    
    return NO;
}
//查找数据语法:select 列名 from  表名 
//关于查找数据的语法就相对复杂一些,下面也只是列举了一部分而已
//简单说一下吧。order by 根据指定的列对查询到的数据进行排序,默认升序,如果要降序则order by 列名 DESC;
//limit 是指获取多少条数据,小于0获取全部,大于0获取limit条
// * 代表所有列。属于将全部列写进去的快捷方法
//where=1,因为where代表条件语句,=1说明绝对为真,属于无约束查询
- (sqlite3_stmt *)selectSQLWithOrderBy:(NSString *)orderBy findStr:(NSString *)findStr whereStr:(NSString *)whereStr limit:(int)limit tableName:(NSString *)tableName
{
    if (!whereStr || whereStr == nil) {
        whereStr = @" where 1=1";
    }else {
        whereStr = [NSString stringWithFormat:@" where 1=1 and %@",whereStr];
    }
    
    if (!findStr || findStr == nil) {
        findStr = @"*";
    }
    
    NSString *limitStr;
    if ( limit > 0 ) {
        limitStr = [NSString stringWithFormat:@" limit %d",limit];
    }else {
        limitStr = @"";
    }
    
    NSString *sql;
    if ( orderBy ) {
        sql = [NSString stringWithFormat:@"select %@ from %@ %@ order by %@ %@",findStr,tableName,whereStr,orderBy,limitStr];
    }else {
        sql = [NSString stringWithFormat:@"select %@ from %@ %@ %@",findStr,tableName,whereStr,limitStr];
    }
    
    NSLog(@"[Select SQL] : %@",sql);
    
    sqlite3_stmt *result;
    
    sqlite3_prepare_v2(sqlite, [sql UTF8String], -1, &result, nil);
    
    return result;
}
//最后一个,返回的值为sqlite3_stmt *对象,意思是已经拿到了数据库数据,这里将获取到的数据转换成OC对象
    NSMutableArray *arr = [NSMutableArray array];
    
    sqlite3_stmt *result = [[DataBase defaultDB] selectSQLWithOrderBy:orderBy findStr:@"page,type,message,create_time" whereStr:whereStr limit:limit tableName:TableName];  //写好条件语句(where)和获取数据条数(limit)
    
    while ( sqlite3_step(result) == SQLITE_ROW) {
        
        
        char *page = (char *)sqlite3_column_text(result,0);
        char *type = (char *)sqlite3_column_text(result,1);
        char *message = (char *)sqlite3_column_text(result,2);
        char *createTime = (char *)sqlite3_column_text(result,3);
        
        NSInteger pageNum = atoi(page); //将char类型转换成整型
        NSInteger type = atoi(type);
        NSString *messageStr = [NSString stringWithUTF8String:message];   //将char字符串编码成OC String类型
        NSString *createTime = [NSString stringWithUTF8String:createTime];
    }
    
    sqlite3_finalize(result);   //最后别忘记写个完成语句

补充一下,数据库的操作不止上面这些,还有很多没有说明的,有兴趣的话可以看看这个网站
http://www.w3school.com.cn/sql/sql_syntax.asp
也是新人,哪里有问题欢迎指出

你可能感兴趣的:(OC中数据库的基本使用)