李战磊 2013-05-19
-(void) addObserver{ //当程序进入后台时执行操作 UIApplication *app = [UIApplication sharedApplication]; [[ NSNotificationCenter defaultCenter] addObserver: self selector:@selector(appwillresignActive) name:UIApplicationWillResignActiveNotification object:app]; } -(void) appwillresignActive{ NSLog(@"监听测试"); }
头部引入
#import "sqlite3.h"
-(void) makeDBinfo{ NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *databaseFilePath=[[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:@"mydb"]; char *errorMsg; //打开或创建数据库 sqlite3 *database; if (sqlite3_open([databaseFilePath UTF8String], &database)!=SQLITE_OK) { sqlite3_close(database); }else { NSLog(@"open sqlite db ok."); } //创建数据库表 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 table ok."); }else { //如果在多个地方使用errorMsg,那么每次使用完毕要清空一下字串,比如这样: NSLog(@"error: %s",errorMsg); sqlite3_free(errorMsg); } // 向表中插入记录 const char *insertSql="insert into persons (name) values(\"张三\")"; if (sqlite3_exec(database, insertSql, NULL, NULL, &errorMsg)==SQLITE_OK) { NSLog(@"insert ok."); }else { //如果在多个地方使用errorMsg,那么每次使用完毕要清空一下字串,比如这样: NSLog(@"error: %s",errorMsg); sqlite3_free(errorMsg); } //结果集的查询,需要用到statement: const char *selectSql="select id,name from persons where name = ? "; sqlite3_stmt *statement; if (sqlite3_prepare_v2(database, selectSql, -1, &statement, nil)==SQLITE_OK) { NSLog(@"select ok."); sqlite3_bind_text(statement, 1, "张三",-1,NULL); 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); } sqlite3_finalize(statement); } sqlite3_close(database); }
constchar *sql_drop_table="drop table if exists t";
constchar *sql_create_table="create table t(id int primary key,msg varchar(128))";
sqlite3_exec(db,sql_drop_table,0,0,&errmsg);
sqlite3_exec(db,sql_create_table,0,0,&errmsg);
sqlite3_exec(db,"insert into t(id,msg) values(1,'Ady Liu')",NULL,NULL,&errmsg);
int i = 0;
sqlite3_stmt *stmt;
char ca[255];
//prepare statement
sqlite3_prepare_v2(db,"insert into t(id,msg) values(?,?)",-1,&stmt,0);
for(i=10;i<20;i++){
sprintf(ca,"HELLO#%i",i);
sqlite3_bind_int(stmt,1,i);
sqlite3_bind_text(stmt,2,ca,strlen(ca),NULL);
sqlite3_step(stmt);
sqlite3_reset(stmt);
}
sqlite3_finalize(stmt)