您好,登錄后才能下訂單哦!
iOS下 Sqlite3 簡單的代碼例子
首先,導(dǎo)入libsqlite3.0.dylib庫
我們,來看一下.h文件
#import <sqlite3.h> @interface ViewController : UIViewController @property (assign,nonatomic)sqlite3* database; -(IBAction)openDB; -(IBAction)createTestList; -(IBAction)insertTable; -(IBAction)queryTable; -(IBAction)deleteTable; -(IBAction)updateTable; @end
//獲取document沙箱路徑 -(NSString*)dataFilePath{ NSArray *myPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *myDocPath = [myPaths objectAtIndex:0]; NSString *filename = [myDocPath stringByAppendingPathComponent:@"sqlite.db"]; NSLog(@"%@",filename); return filename;//這里很神奇,可以定義成任何類型的文件,也可以不定義成.db文件,任何格局都行,定義成.sb文件都行,達到了很好的數(shù)據(jù)隱秘性 }
//創(chuàng)建,打開數(shù)據(jù)庫 -(IBAction)openDB { //獲取數(shù)據(jù)庫路徑 NSString* path = [self dataFilePath]; //若是數(shù)據(jù)庫存在,則用sqlite3_open直接打開(若是數(shù)據(jù)庫不存在sqlite3_open會主動創(chuàng)建) sqlite3_open([path UTF8String], &_database); }
//創(chuàng)建表 -(IBAction)createTestList { const char *createSql="create table if not exists testTable(ID INTEGER PRIMARY KEY AUTOINCREMENT, testID int,testValue text,testName text)"; sqlite3_exec(_database, createSql, NULL, NULL, NULL); }
//插入數(shù)據(jù) -(IBAction)insertTable { const char *insertSql="INSERT INTO testTable(testID, testValue,testName) VALUES(120,'ew','45')"; sqlite3_exec(_database, insertSql, NULL, NULL, nil); }
//查看數(shù)據(jù) -(IBAction)queryTable { [self openDB]; const char *selectSql="select testID,testName from testTable"; 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); } } }
//刪除數(shù)據(jù) -(IBAction)deleteTable { [self openDB]; const char *sql = "DELETE FROM testTable where testName='45'"; sqlite3_exec(_database, sql, NULL, NULL, nil); }
//更改數(shù)據(jù) -(IBAction)updateTable { [self openDB]; const char *sql = "update testTable set testName ='444' WHERE testID =120"; sqlite3_exec(_database, sql, NULL,NULL,NULL); sqlite3_close(_database); }
最后,在XIB中拖四個按鈕與增、刪、改、查 四個方法相關(guān)聯(lián)
Hi,推薦文件給你 "Sqlite例子.zip" http://vdisk.weibo.com/s/HqLZq
http://pan.baidu.com/share/link?shareid=3059825140&uk=3189484501
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。