sqlite3数据库的操作(iphone开发)

  下面是对sqlite3数据库的操作,首先是要倒入类,最基本的,但不要忘记。我对数据库的操作进行了单独的处理,自己看着比较舒服,也好明白,需要用到时,直接调用久好了,也可以有代理,一直没研究,日后好好看看,先总结这些,方便自己查看,忘记时找找,老不用会很快忘记,方便自己吧!

#import </usr/include/sqlite3.h>



#define kFilename @"data.sqlite3"



 

1.打开数据库操作



-(void)openDB {



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



    NSString *documentsDirectory = [paths objectAtIndex:0];



NSString *dataFilePath =  [documentsDirectory stringByAppendingPathComponent:kFilename];



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



sqlite3_close(database);



}



}



2.创建表,结构,类型



- (void)initDB {



char *errorMsg;



NSString *sql = @"CREATE TABLE IF NOT EXISTS USER (USER_ID INTEGER PRIMARY KEY,USERNAME TEXT,PASSWORD TEXT);";



if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK) {



sqlite3_close(database);



}



}



3.执行添加方法



 



- (void)insertUsername:(NSString *)username insertPassword:(NSString *)password {



[self openDB];//调用打开库



[self initDB];//调用创建表



char *errorMsg;



char *update = "INSERT OR REPLACE INTO USER (USERNAME,PASSWORD) VALUES (?,?);";//添加语句



 



NSString *sql = [NSString stringWithFormat:@"SELECT USERNAME,PASSWORD FROM USER"];//查询语句



 



sql = @"DELETE FROM USER;";//删除语句



 



 



sqlite3_stmt *statement;



if (sqlite3_prepare_v2(database, update, -1, &statement, nil) == SQLITE_OK) {



sqlite3_bind_text(statement, 1, [username UTF8String], -1, SQLITE_TRANSIENT);



sqlite3_bind_text(statement, 2, [password UTF8String], -1, SQLITE_TRANSIENT);



}



if (sqlite3_step(statement) != SQLITE_DONE)



NSAssert1(0,@"Error updating table:%s",errorMsg);



sqlite3_finalize(statement);



sqlite3_close(database);



}



 


你可能感兴趣的:(iPhone开发)