iOS App项目中引入SQLite数据库的教程

引入SQLite
sqlite是纯C实现的,所以注定了它是一个跨平台利器,在Android与IOS下均能使用,而且完全可以写出通用的代码,方便我们移植。当然Android和IOS下都有封装过的sqlite给开发者使用,不过这样子一个是不方便移植,另一个是封装后的效率咋样我们也不知道,所以还是原生态的最健康。最后一个重要的原因就是原生的使用也是相当简单。我将在接下来的教程中为您一一讲解。
首先最重要的一点是在工程中导入sqlite,苹果的SDK已经给你包含进来了,所以只要导入一个叫 libsqlite3.0.dylib 的 framework就好了。然后,包含相应的头文件:#import "sqlite3.h"    。
在IOS工程的导入就已经结束了,你可以正常使用了。
在其他工程中,比如android中,嵌入式linux中,我们就需要添加两个文件了 请到 http://sqlite.org/download.html 下载相应的文件,你用哪个平台的就对应下哪个文件,不过我一般下第一个叫做 sqlite-amalgamation-3071000.zip  的文件,这个里面包含了一个 sqlite3.c 与一个 sqlite3.h 。我直接把这两个文件拖到我的工程中去,然后在需要使用的地方把 .h 文件包含进来就好了 。这样比调用编译好的库的好处是我能更方便的调试,我也能对他的功能做一些修改,比如我可以自己在里面添加一套 自己的加密方式,又或者我可以添加几个回调函数来方便与上层交互。或者删掉我们不需要的功能,减少代码冗余。
在我接下来的讲解中,我会用纯C去讲解,虽然我会在苹果的 xcode 环境下去写代码,但是除了库的引用方式不一样以外,其他的都一样,我会尽量避免与平台相关的东西。当然有时候我可能会写一个有UI的Demo,这时候就无可避免地要与平台打交道了,不过这个教程的关键点在于弄懂底层的原理,学会sqlite的API的调用,根据自己的需求封装以及提供接口。
最后附上xcode 中导入sqlite的图:

单击那个加号。然后搜索sqlite3 ,选取 sqlite3.0.dylib, 然后 单击Add。然后你就看到工程中这个库导进来了。

然后在需要调用的地方导入头文件:

SQLite的数据类型
要使用数据库你得先弄清楚他的数据类型,不是吗?sqlite 数据类型及其简单:

  • NULL. 空值
  • INTEGER. 整型
  • REAL.浮点型
  • TEXT.文本类型
  • BLOB. 二进制类型,用来存储文件,比如图片。

以上是sqlite的存储类型,当然,每种类型会根据数据长度有不同的子类型。这个现在不讲, 因为你可以直接使用上述这些大的类型。你知道知道有哪几个类型就好了。以后在实际运用中慢慢熟悉就好了 。

sqlite其实没有强制要求你预先声明数据类型,在实际存储过程中它会根据实际类型来自动转换,不过为了提高效率我们不建议non-datatype。
下面附上一个创建表的代码,主要是让你体会一下数据类型的实际运用:

CREATE TABLE student( 
  name TEXT,  //姓名 
  no INTEGER, //学号 
  totalScore REAL, //总分 
  photo BLOB   //照片 
); 

句柄的定义
要操纵一个数据库你就得有一个这个数据库的句柄(又碰到这个难以理解的词了,不过确实还没得一个更好的词来替代它)。其实你跟本不需要去在乎这个词叫什么,你只要搞清楚他是一个什么玩意儿。就如同鞋子为什么叫鞋子,仔细想想确实也难以理解,不过 清楚他的功能就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的句柄我们就创建完成了,我们以后针对数据库的操作都离不开它了。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。