服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS App使用SQLite之句柄的定义及数据库的基本操作

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

2021-01-20 16:15刘伟 IOS

SQLite中在定义过句柄之后就可以指向数据库,从而利用iOS应用程序进行打开或关闭等各种操作,这里我们就来看一下iOS App使用SQLite之句柄的定义及数据库的基本操作

句柄
要操纵一个数据库你就得有一个这个数据库的句柄(又碰到这个难以理解的词了,不过确实还没得一个更好的词来替代它)。其实你跟本不需要去在乎这个词叫什么,你只要搞清楚他是一个什么玩意儿。就如同鞋子为什么叫鞋子,仔细想想确实也难以理解,不过 清楚他的功能就OK了,不是吗?
句柄在很多地方我们见到过,最常见的就是文件的句柄,我们要操纵一个文件,我们就要取得一个文件的句柄。句柄是个什么东东呢?其实很简单,句柄是一个东东的描述,他被定义为一个结构体,这个结构体可能会包含要描述的东东的具体信息,比如位置、大小、类型等等。我们有了这个描述信息我们就能去找到这个东东,然后操纵它。
一句话:句柄是物体的描述结构体。
我们来看看sqlite的句柄是怎么定义的(不要被吓到了,代码直接跳过就好):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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 里面你要操纵数据库我们先得创建一个句柄,然后后面所有对数据库得操作都会用到这个句柄。

?
1
sqlite3* pdb;

就 这么简单,这样一个ssqlite的句柄我们就创建完成了,我们以后针对数据库的操作都离不开它了。


打开、关闭、创建 数据库
我创建了一个句柄,但是我怎么知道这个句柄指向的是磁盘上哪个数据库文件呢?我们只是创建了一个指针,指向一个 sqlite3 类型的结构体。里面的数据都是空的或者默认的。我们接下来要做的就是去为这个结构体申请内存并填充这个结构体。是不是感觉又被吓到了?这个结构体这么庞大,我们自己去填充还不的猴年马月啊。一切都不用害怕,并不需要我们显式的去填充它,我们只需要告诉它一些最基本的信息,然后调用API让API去帮我们填充。
目前我们只需要告诉这个结构体一个信息,就是数据库文件的路径。然后调用 sqlite3_open 函数就OK了。

?
1
2
3
4
SQLITE_API int sqlite3_open(//SQLITE_API 是个宏,用来标注API的不用理它
 const char *zFilename, 
 sqlite3 **ppDb 
);

第一个参数是路径,const char * 型,第二个参数是数据库句柄的指针,注意是一个二级指针,我们声明的一级指针,所以我们还要加一个取地址符&,请看我下面的实例:

?
1
int ret = sqlite3_open( getFilePath(), &pdb);//


 不要奇怪,其实打开数据库就是获得数据库的一些信息,然后方便我们操纵它,不是吗?通过这个函数 我们把 数据库与 句柄 pdb 绑定在一起了,我们以就通过 这个 pdb 来操纵数据库了。在这个函数中第一个参数是数据库文件的路径(包括文件名),我一般会把路径写成一个函数,这样遵循编码原则(这里用到的原则是一个函数尽量只做一件事情),建议你也这样,好处你自己可以慢慢体会到。我获取路径的函数如下你可以参考一下:

?
1
2
3
4
5
const char* getFilePath(){
  return [[NSString stringWithFormat:@"%@/Documents/db",NSHomeDirectory() ] UTF8String];
      //不好意思这里用到了与IOS相关的一点东西,不过这个也没办法,除非我写成绝对路径,但是那样是行不通的
      // 不过也没关系,你移植到别处肯定也是要改路径的咯,所以移植的时候改一下就好了
}

还有一点就是返回值,返回值我们用来判断是否执行成功。sqlite 中帮我们定义了一系列的宏,用来作为返回值:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#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文件(所以它的安全性还是不大行的,不过作为本地数据库没啥问题)。
数据库打开后我们就可以进行一系列的增删查改的操作了,操作完毕我们就要关闭数据库,不是么?否则怎么释放资源呢?
关闭也很简单:

?
1
SQLITE_API int sqlite3_close(sqlite3 *db);

 这个就不用解释了吧,直接看我的实例:

?
1
sqlite3_close(pdb);// 这里就可以不去考虑返回值了

延伸 · 阅读

精彩推荐
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01