当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS App使用SQLite之句柄的定义及数据库的基本操作

iOS App使用SQLite之句柄的定义及数据库的基本操作

2019年07月24日  | 移动技术网移动技术  | 我要评论

句柄
要操纵一个数据库你就得有一个这个数据库的句柄(又碰到这个难以理解的词了,不过确实还没得一个更好的词来替代它)。其实你跟本不需要去在乎这个词叫什么,你只要搞清楚他是一个什么玩意儿。就如同鞋子为什么叫鞋子,仔细想想确实也难以理解,不过 清楚他的功能就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);// 这里就可以不去考虑返回值了 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网