iOS App使用SQLite之句柄的定義及數(shù)據(jù)庫(kù)的基本操作
句柄
要操縱一個(gè)數(shù)據(jù)庫(kù)你就得有一個(gè)這個(gè)數(shù)據(jù)庫(kù)的句柄(又碰到這個(gè)難以理解的詞了,不過(guò)確實(shí)還沒(méi)得一個(gè)更好的詞來(lái)替代它)。其實(shí)你跟本不需要去在乎這個(gè)詞叫什么,你只要搞清楚他是一個(gè)什么玩意兒。就如同鞋子為什么叫鞋子,仔細(xì)想想確實(shí)也難以理解,不過(guò) 清楚他的功能就OK了,不是嗎?
句柄在很多地方我們見(jiàn)到過(guò),最常見(jiàn)的就是文件的句柄,我們要操縱一個(gè)文件,我們就要取得一個(gè)文件的句柄。句柄是個(gè)什么東東呢?其實(shí)很簡(jiǎn)單,句柄是一個(gè)東東的描述,他被定義為一個(gè)結(jié)構(gòu)體,這個(gè)結(jié)構(gòu)體可能會(huì)包含要描述的東東的具體信息,比如位置、大小、類(lèi)型等等。我們有了這個(gè)描述信息我們就能去找到這個(gè)東東,然后操縱它。
一句話(huà):句柄是物體的描述結(jié)構(gòu)體。
我們來(lái)看看sqlite的句柄是怎么定義的(不要被嚇到了,代碼直接跳過(guò)就好):
struct sqlite3 { sqlite3_vfs *pVfs; /* OS Interface */ int nDb; /* Number of backends currently in use */ Db *aDb; /* All backends */ int flags; /* Miscellaneous flags. See below */ unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ int errCode; /* Most recent error code (SQLITE_*) */ int errMask; /* & result codes with this before returning */ u8 autoCommit; /* The auto-commit flag. */ u8 temp_store; /* 1: file 2: memory 0: default */ u8 mallocFailed; /* True if we have seen a malloc failure */ u8 dfltLockMode; /* Default locking-mode for attached dbs */ signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ u8 suppressErr; /* Do not issue error messages if true */ u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ int nextPagesize; /* Pagesize after VACUUM if >0 */ int nTable; /* Number of tables in the database */ CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ i64 lastRowid; /* ROWID of most recent insert (see above) */ u32 magic; /* Magic number for detect library misuse */ int nChange; /* Value returned by sqlite3_changes() */ int nTotalChange; /* Value returned by sqlite3_total_changes() */ sqlite3_mutex *mutex; /* Connection mutex */ int aLimit[SQLITE_N_LIMIT]; /* Limits */ struct sqlite3InitInfo { /* Information used during initialization */ int iDb; /* When back is being initialized */ int newTnum; /* Rootpage of table being initialized */ u8 busy; /* TRUE if currently initializing */ u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ } init; int nExtension; /* Number of loaded extensions */ void **aExtension; /* Array of shared library handles */ struct Vdbe *pVdbe; /* List of active virtual machines */ int activeVdbeCnt; /* Number of VDBEs currently executing */ int writeVdbeCnt; /* Number of active VDBEs that are writing */ int vdbeExecCnt; /* Number of nested calls to VdbeExec() */ void (*xTrace)(void*,const char*); /* Trace function */ void *pTraceArg; /* Argument to the trace function */ void (*xProfile)(void*,const char*,u64); /* Profiling function */ void *pProfileArg; /* Argument to profile function */ void *pCommitArg; /* Argument to xCommitCallback() */ int (*xCommitCallback)(void*); /* Invoked at every commit. */ void *pRollbackArg; /* Argument to xRollbackCallback() */ void (*xRollbackCallback)(void*); /* Invoked at every commit. */ void *pUpdateArg; void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); #ifndef SQLITE_OMIT_WAL int (*xWalCallback)(void *, sqlite3 *, const char *, int); void *pWalArg; #endif void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); void *pCollNeededArg; sqlite3_value *pErr; /* Most recent error message */ char *zErrMsg; /* Most recent error message (UTF-8 encoded) */ char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */ union { volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ double notUsed1; /* Spacer */ } u1; Lookaside lookaside; /* Lookaside malloc configuration */ #ifndef SQLITE_OMIT_AUTHORIZATION int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); /* Access authorization function */ void *pAuthArg; /* 1st argument to the access auth function */ #endif #ifndef SQLITE_OMIT_PROGRESS_CALLBACK int (*xProgress)(void *); /* The progress callback */ void *pProgressArg; /* Argument to the progress callback */ int nProgressOps; /* Number of opcodes for progress callback */ #endif #ifndef SQLITE_OMIT_VIRTUALTABLE Hash aModule; /* populated by sqlite3_create_module() */ VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ VTable **aVTrans; /* Virtual tables with open transactions */ int nVTrans; /* Allocated size of aVTrans */ VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ #endif FuncDefHash aFunc; /* Hash table of connection functions */ Hash aCollSeq; /* All collating sequences */ BusyHandler busyHandler; /* Busy callback */ int busyTimeout; /* Busy handler timeout, in msec */ Db aDbStatic[2]; /* Static space for the 2 default backends */ Savepoint *pSavepoint; /* List of active savepoints */ int nSavepoint; /* Number of non-transaction savepoints */ int nStatement; /* Number of nested statement-transactions */ u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ i64 nDeferredCons; /* Net deferred constraints this transaction. */ int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY /* The following variables are all protected by the STATIC_MASTER ** mutex, not by sqlite3.mutex. They are used by code in notify.c. ** ** When X.pUnlockConnection==Y, that means that X is waiting for Y to ** unlock so that it can proceed. ** ** When X.pBlockingConnection==Y, that means that something that X tried ** tried to do recently failed with an SQLITE_LOCKED error due to locks ** held by Y. */ sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ void *pUnlockArg; /* Argument to xUnlockNotify */ void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ #endif }; typedef struct sqlite3 sqlite3;//
是不是被嚇到了,沒(méi)關(guān)系,這段代碼本來(lái)就是我貼出來(lái)嚇唬你的,我也沒(méi)認(rèn)真研究過(guò)這個(gè)代碼,也不想去研究,除非哪天有人出高價(jià)請(qǐng)我去研究,我現(xiàn)在只知道怎么用就好了。
這個(gè) sqlite3 結(jié)構(gòu)體就是被用來(lái)描述我們磁盤(pán)里的數(shù)據(jù)庫(kù)文件的,有了這個(gè)描述符我們就可以對(duì)這個(gè)數(shù)據(jù)庫(kù)進(jìn)行各種操作了,操作的具體內(nèi)情我們不必要了解,我們只需要知道怎么去調(diào)用API就好了,當(dāng)然有時(shí)候還是要了解一點(diǎn)點(diǎn)內(nèi)情的,這個(gè)以后碰到再講。
我用這么長(zhǎng)的話(huà)加一大段嚇人的代碼只有一個(gè)目的:不要對(duì)句柄有恐懼感。
好了,開(kāi)始我們的正題,sqlite 里面你要操縱數(shù)據(jù)庫(kù)我們先得創(chuàng)建一個(gè)句柄,然后后面所有對(duì)數(shù)據(jù)庫(kù)得操作都會(huì)用到這個(gè)句柄。
sqlite3* pdb;
就 這么簡(jiǎn)單,這樣一個(gè)ssqlite的句柄我們就創(chuàng)建完成了,我們以后針對(duì)數(shù)據(jù)庫(kù)的操作都離不開(kāi)它了。
打開(kāi)、關(guān)閉、創(chuàng)建 數(shù)據(jù)庫(kù)
我創(chuàng)建了一個(gè)句柄,但是我怎么知道這個(gè)句柄指向的是磁盤(pán)上哪個(gè)數(shù)據(jù)庫(kù)文件呢?我們只是創(chuàng)建了一個(gè)指針,指向一個(gè) sqlite3 類(lèi)型的結(jié)構(gòu)體。里面的數(shù)據(jù)都是空的或者默認(rèn)的。我們接下來(lái)要做的就是去為這個(gè)結(jié)構(gòu)體申請(qǐng)內(nèi)存并填充這個(gè)結(jié)構(gòu)體。是不是感覺(jué)又被嚇到了?這個(gè)結(jié)構(gòu)體這么龐大,我們自己去填充還不的猴年馬月啊。一切都不用害怕,并不需要我們顯式的去填充它,我們只需要告訴它一些最基本的信息,然后調(diào)用API讓API去幫我們填充。
目前我們只需要告訴這個(gè)結(jié)構(gòu)體一個(gè)信息,就是數(shù)據(jù)庫(kù)文件的路徑。然后調(diào)用 sqlite3_open 函數(shù)就OK了。
SQLITE_API int sqlite3_open(//SQLITE_API 是個(gè)宏,用來(lái)標(biāo)注API的不用理它 const char *zFilename, sqlite3 **ppDb );
第一個(gè)參數(shù)是路徑,const char * 型,第二個(gè)參數(shù)是數(shù)據(jù)庫(kù)句柄的指針,注意是一個(gè)二級(jí)指針,我們聲明的一級(jí)指針,所以我們還要加一個(gè)取地址符&,請(qǐng)看我下面的實(shí)例:
int ret = sqlite3_open( getFilePath(), &pdb);//
不要奇怪,其實(shí)打開(kāi)數(shù)據(jù)庫(kù)就是獲得數(shù)據(jù)庫(kù)的一些信息,然后方便我們操縱它,不是嗎?通過(guò)這個(gè)函數(shù) 我們把 數(shù)據(jù)庫(kù)與 句柄 pdb 綁定在一起了,我們以就通過(guò) 這個(gè) pdb 來(lái)操縱數(shù)據(jù)庫(kù)了。在這個(gè)函數(shù)中第一個(gè)參數(shù)是數(shù)據(jù)庫(kù)文件的路徑(包括文件名),我一般會(huì)把路徑寫(xiě)成一個(gè)函數(shù),這樣遵循編碼原則(這里用到的原則是一個(gè)函數(shù)盡量只做一件事情),建議你也這樣,好處你自己可以慢慢體會(huì)到。我獲取路徑的函數(shù)如下你可以參考一下:
const char* getFilePath(){ return [[NSString stringWithFormat:@"%@/Documents/db",NSHomeDirectory() ] UTF8String]; //不好意思這里用到了與IOS相關(guān)的一點(diǎn)東西,不過(guò)這個(gè)也沒(méi)辦法,除非我寫(xiě)成絕對(duì)路徑,但是那樣是行不通的 // 不過(guò)也沒(méi)關(guān)系,你移植到別處肯定也是要改路徑的咯,所以移植的時(shí)候改一下就好了 }
還有一點(diǎn)就是返回值,返回值我們用來(lái)判斷是否執(zhí)行成功。sqlite 中幫我們定義了一系列的宏,用來(lái)作為返回值:
#define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ #define SQLITE_ERROR 1 /* SQL error or missing database */ #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ #define SQLITE_PERM 3 /* Access permission denied */ #define SQLITE_ABORT 4 /* Callback routine requested an abort */ #define SQLITE_BUSY 5 /* The database file is locked */ #define SQLITE_LOCKED 6 /* A table in the database is locked */ #define SQLITE_NOMEM 7 /* A malloc() failed */ #define SQLITE_READONLY 8 /* Attempt to write a readonly database */ #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ #define SQLITE_CORRUPT 11 /* The database disk image is malformed */ #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */ #define SQLITE_EMPTY 16 /* Database is empty */ #define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ #define SQLITE_MISMATCH 20 /* Data type mismatch */ #define SQLITE_MISUSE 21 /* Library used incorrectly */ #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ #define SQLITE_AUTH 23 /* Authorization denied */ #define SQLITE_FORMAT 24 /* Auxiliary database format error */ #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ #define SQLITE_NOTADB 26 /* File opened that is not a database file */ #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ /* end-of-error-codes */
有了這些我們就可以更加方便地調(diào)試我們的代碼了。
好了,進(jìn)入正題,上面這個(gè)函數(shù)就是在數(shù)據(jù)庫(kù)存在的情況下打開(kāi)數(shù)據(jù)庫(kù),不存在的情況下創(chuàng)建數(shù)據(jù)庫(kù),數(shù)據(jù)庫(kù)的名字可以隨便亂取,只要是ASCII字符就好了,因?yàn)閟qlite數(shù)據(jù)庫(kù)本來(lái)就是一個(gè)ASCII文件(所以它的安全性還是不大行的,不過(guò)作為本地?cái)?shù)據(jù)庫(kù)沒(méi)啥問(wèn)題)。
數(shù)據(jù)庫(kù)打開(kāi)后我們就可以進(jìn)行一系列的增刪查改的操作了,操作完畢我們就要關(guān)閉數(shù)據(jù)庫(kù),不是么?否則怎么釋放資源呢?
關(guān)閉也很簡(jiǎn)單:
SQLITE_API int sqlite3_close(sqlite3 *db);
這個(gè)就不用解釋了吧,直接看我的實(shí)例:
sqlite3_close(pdb);// 這里就可以不去考慮返回值了
相關(guān)文章
iOS中的UITableView的重用機(jī)制與加載優(yōu)化詳解
本篇文章主要介紹了iOS中的UITableView的重用機(jī)制與加載優(yōu)化詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02iOS Webview自適應(yīng)實(shí)際內(nèi)容高度的4種方法詳解
這篇文章主要介紹了iOS Webview自適應(yīng)實(shí)際內(nèi)容高度的4種方法詳解,本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09iOS實(shí)現(xiàn)帶指引線(xiàn)的餅狀圖效果(不會(huì)重疊)
餅狀圖對(duì)大家來(lái)說(shuō)應(yīng)該都不陌生,下面這篇文章主要給大家介紹了關(guān)于iOS實(shí)現(xiàn)帶指引線(xiàn)的餅狀圖效果(不會(huì)重疊)的相關(guān)資料,文章通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-04-04iOS實(shí)現(xiàn)視頻下載并自動(dòng)保存到相冊(cè)功能
這篇文章主要為大家詳細(xì)介紹了ios 視頻下載功能實(shí)現(xiàn),并自動(dòng)保存到相冊(cè),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02iOS自定義button抖動(dòng)效果并實(shí)現(xiàn)右上角刪除按鈕
這篇文章主要為大家詳細(xì)介紹了iOS自定義button抖動(dòng)效果并實(shí)現(xiàn)右上角刪除按鈕的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-03-03iOS基于UIScrollView實(shí)現(xiàn)滑動(dòng)引導(dǎo)頁(yè)
這篇文章主要為大家詳細(xì)介紹了iOS基于UIScrollView實(shí)現(xiàn)滑動(dòng)引導(dǎo)頁(yè)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01iOS 10撥打系統(tǒng)電話(huà)彈出框延遲出現(xiàn)問(wèn)題的解決
iOS10的到來(lái),帶來(lái)了條幅和鎖屏界面的重新設(shè)計(jì),美觀又好看,再加上抬腕喚醒功能,查看需要的信息確實(shí)更便捷了,還能快捷回復(fù)一些通知,十分輕松,但同樣有問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于iOS 10撥打系統(tǒng)電話(huà)彈出框延遲出現(xiàn)問(wèn)題的解決方法,需要的朋友可以參考下。2017-10-10