首先,添加framework:libsqlite3.0.dylib 需要在对应文件的头文件中加入: #import "/usr/include/sqlite3.h" 并在Frameworks中加入所需的库,否则会报错: Undefined symbols: "_sqlite3_open", referenced from: 加入库的方法是: image 选择sqlite库: image 选择完的效果: image 下面是代码: //sqlite [self openDataBase]; //[self createTable]; //[self insertTable]; [self queryTable]; [self deleteTable]; [self queryTable]; 实现: //open database - (void)openDataBase { NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask , YES); NSString *databaseFilePath=[[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:@"db.sql"]; if (sqlite3_open([databaseFilePath UTF8String], &database)==SQLITE_OK) { NSLog(@"open sqlite db ok."); } else { NSLog( @"can not open sqlite db " ); //close database sqlite3_close(database); } } //create table - (void)createTable { char *errorMsg; const char *createSql="create table if not exists persons (id integer primary key autoincrement,name text)"; if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK) { NSLog(@"create ok."); } else { NSLog( @"can not create table" ); [self ErrorReport:(NSString *)createSql]; } } //insert table - (void)insertTable { char *errorMsg; const char *insertSql="insert into persons (name) values ('田周辉')"; if (sqlite3_exec(database, insertSql, NULL, NULL, &errorMsg)==SQLITE_OK) { NSLog(@"insert ok."); } else { NSLog( @"can not insert it to table" ); [self ErrorReport: (NSString *)insertSql]; } } //error - (void)ErrorReport: (NSString *)item { char *errorMsg; if (sqlite3_exec(database, (const char *)item, NULL, NULL, &errorMsg)==SQLITE_OK) { NSLog(@"%@ ok.",item); } else { NSLog(@"error: %s",errorMsg); sqlite3_free(errorMsg); } } //query table - (void)queryTable { const char *selectSql="select id,name from persons"; sqlite3_stmt *statement; if (sqlite3_prepare_v2(database, selectSql, -1, &statement, nil)==SQLITE_OK) { NSLog(@"select ok."); while (sqlite3_step(statement)==SQLITE_ROW)//SQLITE_OK SQLITE_ROW { int _id=sqlite3_column_int(statement, 0); NSString *name=[[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding]; NSLog(@"row>>id %i, name>> %@",_id,name); } } else { //error [self ErrorReport: (NSString *)selectSql]; } sqlite3_finalize(statement); } //delete table - (void)deleteTable { char *errorMsg; [self openDataBase]; const char *sql = "DELETE FROM persons where id=24"; if (sqlite3_exec(database, sql, NULL, NULL, &errorMsg)==SQLITE_OK) { NSLog(@"delete ok."); } else { NSLog( @"can not delete it" ); [self ErrorReport: (NSString *)sql]; } } 命令行: sqlite3 database //创建数据库 crate table tableFile(id smallint, file_name varchar(256), up_state smallint, file_size smallint); //创建一个表格 insert into tableFile values(1, "200110101.rcu", 100, 4500); //插入数据 5 如何访问SQLite3数据库 sqlite3_open //打开数据库 sqlite3_prepare //将UTF-8格式的SQL语句转换为指向已备语句的指针 sqlite3_column_string //返回某一行的字符串 sqlite3_finalize //删除一条已备语句 sqlite3_close //关闭数据库 6 source code - (id)lookupSingularSQL:(NSString *)sql forType:(NSString *)rettype { sqlite3_stmt *statement; id result; if (statement = [self prepare:sql]) { if (sqlite3_step(statement) == SQLITE_ROW) { if ([rettype compare:@"text"] == NSOrderedSame) { char temp_buf[256]; memset(temp_buf, 0, 256); sprintf(temp_buf, "%s %s %s %s", (char *)sqlite3_column_text(statement,0), (char *)sqlite3_column_text(statement,1), (char *)sqlite3_column_text(statement,2), (char *)sqlite3_column_text(statement,3) ); result = [NSString stringWithUTF8String:temp_buf]; //result = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,0)]; } else if ([rettype compare:@"integer"] == NSOrderedSame) { result = (id)sqlite3_column_int(statement,0); } } } sqlite3_finalize(statement); return result; } 应该有个成员变量,比如我的代码: @interface DetailViewController : UIViewController { UIPopoverController *popoverController; UIToolbar *toolbar; id detailItem; UILabel *detailDescriptionLabel; sqlite3 *database; 打开数据库 SQLite数据库是文件数据库,是保存在文件系统中的。因此需要知道文件保存到哪里,可参见iOS中对文件的操作。比如本文保存到Documents目录下。代码: NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask , YES); NSString *databaseFilePath=[[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:@"mydb"]; if (sqlite3_open([databaseFilePath UTF8String], &database)==SQLITE_OK) { NSLog(@"open sqlite db ok."); } 通过ssh查看Documents目录,发现mydb文件已经创建。sqlite的策略是如果有该文件就打开,如果没有就创建文件,也就是创建数据库。 这里要注意,使用的是C语法,sqlite3_open传入的是database的地址。 关闭数据库 数据库使用完毕后,要关闭,比如退出应用的时候: - (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; sqlite3_close(database); self.popoverController = nil; } 建表语句 数据库打开以后,如果没有表,建表: char *errorMsg; const char *createSql="create table if not exists persons (id integer primary key autoincrement,name text)"; if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK) { NSLog(@"create ok."); } 这里要特别注意errorMsg传的是地址,因为该函数要通过地址引用来写报错字符信息。 向表中插入记录 和建表语句类似: const char *insertSql="insert into persons (name) values(‘张三’)"; if (sqlite3_exec(database, insertSql, NULL, NULL, &errorMsg)==SQLITE_OK) { NSLog(@"insert ok."); } 错误信息的处理 如果在多个地方使用errorMsg,那么每次使用完毕要清空一下字串,比如这样: if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK) { NSLog(@"create ok."); }else { NSLog(@"error: %s",errorMsg); sqlite3_free(errorMsg); } 查询结果集 结果集的查询,需要用到statement: const char *selectSql="select id,name from persons"; sqlite3_stmt *statement; if (sqlite3_prepare_v2(database, selectSql, -1, &statement, nil)==SQLITE_OK) { NSLog(@"select ok."); } while (sqlite3_step(statement)==SQLITE_ROW) { int _id=sqlite3_column_int(statement, 0); char *name=(char *)sqlite3_column_text(statement, 1); NSLog(@"row>>id %i, name %s",_id,name); } sqlite3_finalize(statement); 不过这里有个问题,看看打印的日志: image 乱码。因为直接用的char类型来做的。 解决办法是,用nsstring替代char: while (sqlite3_step(statement)==SQLITE_ROW) { int _id=sqlite3_column_int(statement, 0); NSString *name=[[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding]; NSLog(@"row>>id %i, name %@",_id,name); } char生成nsstring的时候做一次显式的编码。问题解决: image 这说明: 写入数据库,用char的方式没有问题,写入数据库的编码是对的; 从库中取出,可能默认使用ascii解码,造成显示乱码。 使用sqlite c api,要经常参考官方函数文档:http://www.sqlite.org/c3ref/funclist.html