iOS App使用SQLite之控制代碼的定義及資料庫的基本操作_IOS

來源:互聯網
上載者:User

控制代碼
要操縱一個資料庫你就得有一個這個資料庫的控制代碼(又碰到這個難以理解的詞了,不過確實還沒得一個更好的詞來替代它)。其實你跟本不需要去在乎這個詞叫什麼,你只要搞清楚他是一個什麼玩意兒。就如同鞋子為什麼叫鞋子,仔細想想確實也難以理解,不過 清楚他的功能就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);// 這裡就可以不去考慮傳回值了 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.