使用sqlite3操作

前端之家收集整理的这篇文章主要介绍了使用sqlite3操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在ios上使用sqlite3实现创建数据库,插入或更新数据记录,删除记录,查询记录功能

创建数据表:

create table sudent {

integer id primary key,

text name,

text age,

}


首先要引入 libsqlite3.dylib

//////.h文件

#import <Foundation/Foundation.h>

#import "sqlite3.h"

@interface myDBRecord : NSObject

+(NSString *)dataFilePath;

+(BOOL)openDataBase;

+(void)createTable;

+(void)insertRecord:(NSString *)name Age:(NSString *)age ;

+(void)deleteAllRecord ;

+(NSMutableArray *)selectRecordWidthsql:(NSString *)sql;

@end

/////.m文件

#import "myDBRecord.h"

@implementation myDBRecord

static sqlite3 *database;

//数据库目录

+(NSString *)dataFilePath {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

return [documentsDirectory stringByAppendingPathComponent:@"MyDB.db"];

}

//打开数据库

+(BOOL)openDataBase{

if (sqlite3_open([[myDBRecord dataFilePath] UTF8String],&database)!=sqlITE_OK) {

sqlite3_close(database);

NSLog(@"打开数据表失败。");

return NO;

}

return YES;

}

// 创建student数据表

+(void)createTable{

if ([self openDataBase]) {

char *errorMsg;

char *studentTable = "create table if not exists student (id integer primary key,my_name text,my_age text);";

if (sqlite3_exec (database,studentTable,NULL,&errorMsg) != sqlITE_OK) {

sqlite3_close(database);

NSLog(@"创建数据表失败。%@",errorMsg);

}

}

sqlite3_close(database);

}

// 插入记录数

+(void)insertRecord:(NSString *)name Age:(NSString *)age {

char *errorMsg = NULL;

//

char *insertsql = "INSERT OR REPLACE INTO student (my_name,my_age) VALUES (?,?)";

sqlite3_stmt *stmt;

if (sqlite3_prepare_v2(database,insertsql,-1,&stmt,nil) == sqlITE_OK) {

sqlite3_bind_text(stmt,1,[name UTF8String],NULL);

sqlite3_bind_text(stmt,2,[age UTF8String],NULL);

}

if (sqlite3_step(stmt) != sqlITE_DONE) {

NSLog(@"插入记录数失败。%@",errorMsg);

}

sqlite3_finalize(stmt);

//

}

//删除记录数

+(void)deleteAllRecord {

//

char *errorMsg;

char *studentTable = "delete from student;";

if (sqlite3_exec (database,&errorMsg) != sqlITE_OK) {

sqlite3_close(database);

NSLog(@"删除记录数失败。%@",errorMsg);

}

//

}

//查询数据数 sql = @"select * from student"

+(NSMutableArray *)selectRecordWidthsql:(NSString *)sql {

NSMutableArray *arr=[[NSMutableArray alloc] init];

//

sqlite3_stmt *stmt;

if(sqlite3_prepare_v2(database,[sql UTF8String],nil) == sqlITE_OK){

while (sqlite3_step(stmt) == sqlITE_ROW) {

char *chmy_name = (char *)sqlite3_column_text(stmt,2); //2个字段

char *chmy_age = (char *)sqlite3_column_text(stmt,3);

if (chmy_name!=nil) {

[arr addObject:[NSString stringWithUTF8String:chmy_name]];

}

if (chmy_age!=nil) {

[arr addObject:[NSString stringWithUTF8String:chmy_age]];

}

}

sqlite3_finalize(stmt);

}

//

return [arr autorelease];

}

@end

原文链接:https://www.f2er.com/sqlite/200948.html

猜你在找的Sqlite相关文章