句柄
要把持一個數據庫你就得有一個這個數據庫的句柄(又碰著這個難以懂得的詞了,不外確切還沒得一個更好的詞來替換它)。其實你跟本不須要去在意這個詞叫甚麼,你只需弄清晰他是一個甚麼玩藝兒。就好像鞋子為何叫鞋子,細心想一想確切也難以懂得,不外 清晰他的功效就OK了,不是嗎?
句柄在許多處所我們見到過,最多見的就是文件的句柄,我們要把持一個文件,我們就要獲得一個文件的句柄。句柄是個甚麼東東呢?其實很簡略,句柄是一個東東的描寫,他被界說為一個構造體,這個構造體能夠會包括要描寫的東東的詳細信息,好比地位、年夜小、類型等等。我們有了這個描寫信息我們就可以去找到這個東東,然後把持它。
一句話:句柄是物體的描寫構造體。
我們來看看SQLite的句柄是怎樣界說的(不要被嚇到了,代碼直接跳過就好):
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;//
是否是被嚇到了,沒緊要,這段代碼原來就是我貼出來恫嚇你的,我也沒賣力研討過這個代碼,也不想去研討,除非哪天有人出低價請我去研討,我如今只曉得怎樣用就行了。
這個 sqlite3 構造體就是被用來描寫我們磁盤裡的數據庫文件的,有了這個描寫符我們便可以對這個數據庫停止各類操作了,操作的詳細內幕我們不用要懂得,我們只須要曉得怎樣去挪用API就行了,固然有時刻照樣要懂得一點點內幕的,這個今後碰著再講。
我用這麼長的話加一年夜段嚇人的代碼只要一個目標:不要對句柄有恐怖感。
好了,開端我們的正題,sqlite 外面你要把持數據庫我們先得創立一個句柄,然後前面一切對數據庫得操作都邑用到這個句柄。
sqlite3* pdb;
就 這麼簡略,如許一個ssqlite的句柄我們就創立完成了,我們今後針對數據庫的操作都離不開它了。
翻開、封閉、創立 數據庫
我創立了一個句柄,然則我怎樣曉得這個句柄指向的是磁盤上哪一個數據庫文件呢?我們只是創立了一個指針,指向一個 sqlite3 類型的構造體。外面的數據都是空的或許默許的。我們接上去要做的就是去為這個構造體請求內存並填充這個構造體。是否是感到又被嚇到了?這個構造體這麼宏大,我們本身去填充還不的猴年馬月啊。一切都不消畏懼,其實不須要我們顯式的去填充它,我們只須要告知它一些最根本的信息,然後挪用API讓API去幫我們填充。
今朝我們只須要告知這個構造體一個信息,就是數據庫文件的途徑。然後挪用 sqlite3_open 函數就OK了。
SQLITE_API int sqlite3_open(//SQLITE_API 是個宏,用來標注API的不消理它 const char *zFilename, sqlite3 **ppDb );
第一個參數是途徑,const char * 型,第二個參數是數據庫句柄的指針,留意是一個二級指針,我們聲明的一級指針,所以我們還要加一個取地址符&,請看我上面的實例:
int ret = sqlite3_open( getFilePath(), &pdb);//
不要奇異,其實翻開數據庫就是取得數據庫的一些信息,然前方便我們把持它,不是嗎?經由過程這個函數 我們把 數據庫與 句柄 pdb 綁定在一路了,我們以就經由過程 這個 pdb 來把持數據庫了。在這個函數中第一個參數是數據庫文件的途徑(包含文件名),我普通會把途徑寫成一個函數,如許遵守編碼准繩(這裡用到的准繩是一個函數盡可能只做一件工作),建議你也如許,利益你本身可以漸漸領會到。我獲得途徑的函數以下你可以參考一下:
const char* getFilePath(){ return [[NSString stringWithFormat:@"%@/Documents/db",NSHomeDirectory() ] UTF8String]; //欠好意思這裡用到了與IOS相干的一點器械,不外這個也沒方法,除非我寫成相對途徑,然則那樣是行欠亨的 // 不外也沒緊要,你移植到別處確定也是要改途徑的咯,所以移植的時刻改一下就行了 }
還有一點就是前往值,前往值我們用來斷定能否履行勝利。sqlite 中幫我們界說了一系列的宏,用來作為前往值:
#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 */
有了這些我們便可以加倍便利地調試我們的代碼了。
好了,進入正題,下面這個函數就是在數據庫存在的情形下翻開數據庫,不存在的情形下創立數據庫,數據庫的名字可以隨意亂取,只需是ASCII字符就行了,由於sqlite數據庫原來就是一個ASCII文件(所以它的平安性照樣不年夜行的,不外作為當地數據庫沒啥成績)。
數據庫翻開後我們便可以停止一系列的增刪查改的操作了,操作終了我們就要封閉數據庫,不是麼?不然怎樣釋放資本呢?
封閉也很簡略:
SQLITE_API int sqlite3_close(sqlite3 *db);
這個就不消說明了吧,直接看我的實例:
sqlite3_close(pdb);// 這裡便可以不去斟酌前往值了
【iOS App應用SQLite之句柄的界說及數據庫的根本操作】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!