SQLITE3 使用总结
前序: 一、版本 二、基本编译 include “./sqlite3.h”}; 三、SQLITE操作入门 sqlite 里最常用到的是 sqlite3 * 类型。从数据库打开开始,sqlite就要为这个类型准备好内存,直到数据库关闭,整个过程都需要用到这个类型。当数据库打开时开始,这个类型的变量就代表了你要操作的数据库。下面再详细介绍。 int sqlite3_open( 文件名,sqlite3 ** ); int sqlite3_close(sqlite3 *); include “./sqlite3.h”}; //打开数据库 //数据库打开成功 2 SQL语句操作 (1)执行sql语句 int sqlite3_exec(sqlite3*,const char sql,sqlite3_callback,void ,char **errmsg ); typedef int (sqlite3_callback)(void,int,char**,char**); //这里,我不使用 para 参数。忽略它的存在. int i; printf( “记录包含 %d 个字段/n”,n_column ); int main( int,char ** ) result = sqlite3_open( “c://Dcg_database.db”,&db ); if( result != SQLITE_OK ) { //数据库打开失败 return -1; //数据库操作代码 //插入一些记录 result = sqlite3_exec( db,“insert into MyTable_1( name ) values ( ‘骑单车’ )”,“insert into MyTable_1( name ) values ( ‘坐汽车’ )”,errmsg ); //开始查询数据库 //关闭数据库 通过上面的例子,应该可以知道如何打开一个数据库,如何做数据库基本操作。 (3)不使用回调查询数据库 上面介绍的 sqlite3_exec 是使用回调来执行 select 操作。还有一个方法可以直接查询而不需要回调。但是,我个人感觉还是回调好,因为代码可以更加整齐,只不过用回调很麻烦,你得声明一个函数,如果这个函数是类成员函数,你还不得不把它声明成 static 的(要问为什么?这又是C++基础了。C++成员函数实际上隐藏了一个参数:this,C++调用类的成员函数的时候,隐含把类指针当成函数的第一个参数传递进去。结果,这造成跟前面说的 sqlite 回调函数的参数不相符。只有当把成员函数声明成 static 时,它才没有多余的隐含的this参数)。 result = sqlite3_open( “c://Dcg_database.db”,&db ); //数据库操作代码 for( i = 0; i < nRow ; i++ ) { printf( “第 %d 条记录/n”,i+1 ); for( j = 0 ; j < nColumn; j++ ) { printf( “字段名:%s ?> 字段值:%s/n”,dbResult[j],dbResult [index] ); ++index; // dbResult 的字段值是连续的,从第0索引到第 nColumn - 1索引都是字段名称,从第 nColumn 索引开始,后面都是字段值,它把一个二维的表(传统的行列表示法)用一个扁平的形式来表示 } printf( “-------/n” ); } } //到这里,不论数据库查询是否成功,都释放 char** 查询结果,使用 sqlite 提供的功能来释放 //关闭数据库 到这个例子为止,sqlite3 的常用用法都介绍完了。 3 操作二进制 (1)写入二进制 下面说写二进制的步骤。 (2)读出二进制 下面说读二进制的步骤。 下面开始获取 file_content 的值,因为 file_content 是二进制,因此我需要得到它的指针,还有它的长度: (3)重复使用 sqlite3_stmt 结构 如果你需要重复使用 sqlite3_prepare 解析好的 sqlite3_stmt 结构,需要用函数: sqlite3_reset。 typedef struct sqlite3 sqlite3;
int sqlite3_open(const char*,sqlite3**);
int sqlite3_open16(const void*,sqlite3**);
int sqlite3_close(sqlite3*);
const char *sqlite3_errmsg(sqlite3*);
const void *sqlite3_errmsg16(sqlite3*);
int sqlite3_errcode(sqlite3*);
sqlite3_open() 函数返回一个整数错误代码,而不是像第二版中一样返回一个指向sqlite3结构体的指针. sqlite3_open() 和 sqlite3_open16() 的不同之处在于sqlite3_open16() 使用UTF-16编码(使用本地主机字节顺序)传递数据库文件名. 如果要创建新数据库,sqlite3_open16() 将内部文本转换为UTF-16编码,反之sqlite3_open() 将文本转换为UTF-8编码. #define SQLITE_OK 0 /* Successful result */
#define SQLITE_ERROR 1 /* SQL error or missing database */
#define SQLITE_INTERNAL 2 /* An 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 sqlite_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 /* (Internal Only) Table or record not found */
#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 /* (Internal Only) Database table is empty */
#define SQLITE_SCHEMA 17 /* The database schema changed */
#define SQLITE_TOOBIG 18 /* Too much data for one row of a table */
#define SQLITE_CONSTRAINT 19 /* Abort due to contraint 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_ROW 100 /* sqlite_step() has another row ready */
#define SQLITE_DONE 101 /* sqlite_step() has finished executing */
(2)执行 SQL 语句 typedef int (sqlite_callback)(void,char**); typedef struct sqlite3_stmt sqlite3_stmt;
int sqlite3_prepare(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
int sqlite3_prepare16(sqlite3*,const void*,const void**);
int sqlite3_finalize(sqlite3_stmt*);
int sqlite3_reset(sqlite3_stmt*);
sqlite3_prepare 接口把一条SQL语句编译成字节码留给后面的执行函数. 使用该接口访问数据库是当前比较好的的一种方法. int sqlite3_bind_blob(sqlite3_stmt*,int n,void(*)(void*));
int sqlite3_bind_double(sqlite3_stmt*,double);
int sqlite3_bind_int(sqlite3_stmt*,int);
int sqlite3_bind_int64(sqlite3_stmt*,long long int);
int sqlite3_bind_null(sqlite3_stmt*,int);
int sqlite3_bind_text(sqlite3_stmt*,const char*,void(*)(void*));
int sqlite3_bind_text16(sqlite3_stmt*,void(*)(void*));
int sqlite3_bind_value(sqlite3_stmt*,const sqlite3_value*);
以上是 sqlite3_bind 所包含的全部接口,它们是用来给SQL声明中的通配符赋值的. 没有绑定的通配符则被认为是空值. 绑定上的值不会被sqlite3_reset()函数重置. 但是在调用了sqlite3_reset()之后所有的通配符都可以被重新赋值. int sqlite3_step(sqlite3_stmt*);
如果SQL返回了一个单行结果集,sqlite3_step() 函数将返回 SQLITE_ROW,如果SQL语句执行成功或者正常将返回 SQLITE_DONE,否则将返回错误代码. 如果不能打开数据库文件则会返回 SQLITE_BUSY . 如果函数的返回值是 SQLITE_ROW,那么下边的这些方法可以用来获得记录集行中的数据: const void *sqlite3_column_blob(sqlite3_stmt*,int iCol);
int sqlite3_column_bytes(sqlite3_stmt*,int iCol);
int sqlite3_column_bytes16(sqlite3_stmt*,int iCol);
int sqlite3_column_count(sqlite3_stmt*);
const char *sqlite3_column_decltype(sqlite3_stmt *,int iCol);
const void *sqlite3_column_decltype16(sqlite3_stmt *,int iCol);
double sqlite3_column_double(sqlite3_stmt*,int iCol);
int sqlite3_column_int(sqlite3_stmt*,int iCol);
long long int sqlite3_column_int64(sqlite3_stmt*,int iCol);
const char *sqlite3_column_name(sqlite3_stmt*,int iCol);
const void *sqlite3_column_name16(sqlite3_stmt*,int iCol);
const unsigned char *sqlite3_column_text(sqlite3_stmt*,int iCol);
const void *sqlite3_column_text16(sqlite3_stmt*,int iCol);
int sqlite3_column_type(sqlite3_stmt*,int iCol);
sqlite3_column_count()函数返回结果集中包含的列数. sqlite3_column_count() 可以在执行了 sqlite3_prepare()之后的任何时刻调用. sqlite3_data_count()除了必需要在sqlite3_step()之后调用之外,其他跟sqlite3_column_count() 大同小异. 如果调用sqlite3_step() 返回值是 SQLITE_DONE 或者一个错误代码,则此时调用sqlite3_data_count() 将返回 0 ,然而 sqlite3_column_count() 仍然会返回结果集中包含的列数. #define SQLITE_INTEGER 1
#define SQLITE_FLOAT 2
#define SQLITE_TEXT 3
#define SQLITE_BLOB 4
#define SQLITE_NULL 5
sqlite3_column_decltype() 则用来返回该列在 CREATE TABLE 语句中声明的类型. 它可以用在当返回类型是空字符串的时候. sqlite3_column_name() 返回第N列的字段名. sqlite3_column_bytes() 用来返回 UTF-8 编码的BLOBs列的字节数或者TEXT字符串的字节数. sqlite3_column_bytes16() 对于BLOBs列返回同样的结果,但是对于TEXT字符串则按 UTF-16 的编码来计算字节数. sqlite3_column_blob() 返回 BLOB 数据. sqlite3_column_text() 返回 UTF-8 编码的 TEXT 数据. sqlite3_column_text16() 返回 UTF-16 编码的 TEXT 数据. sqlite3_column_int() 以本地主机的整数格式返回一个整数值. sqlite3_column_int64() 返回一个64位的整数. 最后,sqlite3_column_double() 返回浮点数. 可以使用以下的方法来创建用户自定义的SQL函数: typedef struct sqlite3_value sqlite3_value;
int sqlite3_create_function(
sqlite3 *,const char *zFunctionName,int nArg,int eTextRep,void*,void (*xFunc)(sqlite3_context*,sqlite3_value**),void (*xStep)(sqlite3_context*,void (*xFinal)(sqlite3_context*)
);
int sqlite3_create_function16(
sqlite3*,const void *zFunctionName,void (*xFinal)(sqlite3_context*)
);
#define SQLITE_UTF8 1
#define SQLITE_UTF16 2
#define SQLITE_UTF16BE 3
#define SQLITE_UTF16LE 4
#define SQLITE_ANY 5
nArg 参数用来表明自定义函数的参数个数. 如果参数值为0,则表示接受任意个数的参数. 用 eTextRep 参数来表明传入参数的编码形式. 参数值可以是上面的五种预定义值. SQLite3 允许同一个自定义函数有多种不同的编码参数的版本. 数据库引擎会自动选择转换参数编码个数最少的版本使用. const void *sqlite3_value_blob(sqlite3_value*);
int sqlite3_value_bytes(sqlite3_value*);
int sqlite3_value_bytes16(sqlite3_value*);
double sqlite3_value_double(sqlite3_value*);
int sqlite3_value_int(sqlite3_value*);
long long int sqlite3_value_int64(sqlite3_value*);
const unsigned char *sqlite3_value_text(sqlite3_value*);
const void *sqlite3_value_text16(sqlite3_value*);
int sqlite3_value_type(sqlite3_value*);
上面的函数调用以下的API来获得上下文内容和返回结果: void *sqlite3_aggregate_context(sqlite3_context*,int nbyte);
void *sqlite3_user_data(sqlite3_context*);
void sqlite3_result_blob(sqlite3_context*,void(*)(void*));
void qlite3_result_double(sqlite3_context*,double);
void sqlite3_result_error(sqlite3_context*,int);
void sqlite3_result_error16(sqlite3_context*,int);
void sqlite3_result_int(sqlite3_context*,int);
void sqlite3_result_int64(sqlite3_context*,long long int);
void sqlite3_result_null(sqlite3_context*);
void sqlite3_result_text(sqlite3_context*,void(*)(void*));
void sqlite3_result_text16(sqlite3_context*,void(*)(void*));
void sqlite3_result_value(sqlite3_context*,sqlite3_value*);
void *sqlite3_get_auxdata(sqlite3_context*,int);
void sqlite3_set_auxdata(sqlite3_context*,void*,void (*)(void*));
(4)用户自定义排序规则 下面的函数用来实现用户自定义的排序规则: sqlite3_create_collation(sqlite3*,const char *zName,int(*xCompare)(void*,const void*,const void*));
sqlite3_create_collation16(sqlite3*,const void *zName,const void*));
sqlite3_collation_needed(sqlite3*,void(*)(void*,sqlite3*,const char*));
sqlite3_collation_needed16(sqlite3*,const void*));
sqlite3_create_collation() 函数用来声明一个排序序列和实现它的比较函数. 比较函数只能用来做文本的比较. eTextRep 参数可以取如下的预定义值 SQLITE_UTF8,SQLITE_UTF16LE,SQLITE_UTF16BE,SQLITE_ANY,用来表示比较函数所处理的文本的编码方式. 同一个自定义的排序规则的同一个比较函数可以有 UTF-8,UTF-16LE 和 UTF-16BE 等多个编码的版本. sqlite3_create_collation16()和sqlite3_create_collation() 的区别也仅仅在于排序名称的编码是 UTF-16 还是 UTF-8. 五、给数据库加密 1 必要的宏 #ifndef SQLITE_HAS_CODEC
#define SQLITE_HAS_CODEC
#endif
如果你在代码里定义了此宏,但是还能够正常编译,那么应该是操作没有成功。因为你应该会被编译器提示有一些函数无法链接才对。如果你用的是 VC 2003,你可以在“解决方案”里右键点击你的工程,然后选“属性”,找到“C/C++”,再找到“命令行”,在里面手工添加“/D “SQLITE_HAS_CODEC””。 这是正常的,因为Sqlite只留了接口而已,并没有给出实现。 2自己实现加解密接口函数 这里要说一点的是,我另外新建了两个文件:crypt.c和crypt.h。 ```
#ifndef DCG_SQLITE_CRYPT_FUNC_
#define DCG_SQLITE_CRYPT_FUNC_
/***********
董淳光写的 SQLITE 加密关键函数库 /* /* endif其中的 crypt.c 如此定义: #include "./crypt.h"
#include "memory.h"
/*********** 关键加密函数 ***********/
int My_Encrypt_Func( unsigned char * pData,unsigned int data_len,const char * key,unsigned int len_of_key )
{
return 0;
}
/*********** 关键解密函数 ***********/
int My_DeEncrypt_Func( unsigned char * pData,unsigned int len_of_key )
{
return 0;
}
这个文件很容易看,就两函数,一个加密一个解密。传进来的参数分别是待处理的数据、数据长度、密钥、密钥长度。 # define SQLITE_DEFAULT_PAGE_SIZE 1024
你可以改动这个值,不过还是建议没有必要不要去改它。 上面写了两个扩展函数,如何把扩展函数跟 Sqlite 挂接起来,这个过程说起来比较麻烦。我直接贴代码。 #ifdef SQLITE_HAS_CODEC
#include "./crypt.h"
/* ***********/
void sqlite3pager_free_codecarg(void *pArg);
#endif
这个函数之所以要在 sqlite3.c 开头声明,是因为下面在 sqlite3.c 里面某些函数里要插入这个函数调用。所以要提前声明。 其次,在sqlite3.c文件里搜索“sqlite3PagerClose”函数,要找到它的实现代码(而不是声明代码)。 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
/* A malloc() cannot fail in sqlite3ThreadData() as one or more calls to
** malloc() must have already been made by this thread before it gets
** to this point. This means the ThreadData must have been allocated already
** so that ThreadData.nAlloc can be set.
*/
ThreadData *pTsd = sqlite3ThreadData();
assert( pPager );
assert( pTsd && pTsd->nAlloc );
#endif
需要在这部分后面紧接着插入: #ifdef SQLITE_HAS_CODEC
sqlite3pager_free_codecarg(pPager->pCodecArg);
#endif
这里要注意,sqlite3PagerClose 函数大概也是 3.3.17版本左右才改名的,以前版本里是叫 “sqlite3pager_close”。因此你在老版本sqlite代码里搜索“sqlite3PagerClose”是搜不到的。 最后,往sqlite3.c 文件下找。找到最后一行: /**** End of main.c **************************************/ 在这一行后面,接上本文最下面的代码段。 这里我给出我已经修改好的 sqlite3.c 和 sqlite3.h 文件。 实际上,你可以在sqlite3_open函数之后,到 sqlite3_close 函数之前任意位置调用 sqlite3_key 来设置密码。 i = sqlite3_rekey( db,0 );
来完成密码清空功能。 4 sqlite3.c 最后添加代码段 /*** 董淳光定义的加密函数 ***/
#ifdef SQLITE_HAS_CODEC
/*** 加密结构 ***/
#define CRYPT_OFFSET 8
typedef struct _CryptBlock
{
BYTE* ReadKey; // 读数据库和写入事务的密钥
BYTE* WriteKey; // 写入数据库的密钥
int PageSize; // 页的大小
BYTE* Data;
} CryptBlock,*LPCryptBlock;
#ifndef DB_KEY_LENGTH_BYTE /*密钥长度*/
#define DB_KEY_LENGTH_BYTE 16 /*密钥长度*/
#endif
#ifndef DB_KEY_PADDING /*密钥位数不足时补充的字符*/
#define DB_KEY_PADDING 0x33 /*密钥位数不足时补充的字符*/
#endif
/*** 下面是编译时提示缺少的函数 ***/
/** 这个函数不需要做任何处理,获取密钥的部分在下面 DeriveKey 函数里实现 **/
void sqlite3CodecGetKey(sqlite3* db,int nDB,void** Key,int* nKey)
{
return ;
}
/*被sqlite 和 sqlite3_key_interop 调用,附加密钥到数据库.*/
int sqlite3CodecAttach(sqlite3 *db,int nDb,const void *pKey,int nKeyLen);
/** 这个函数好像是 sqlite 3.3.17前不久才加的,以前版本的sqlite里没有看到这个函数 这个函数我还没有搞清楚是做什么的,它里面什么都不做直接返回,对加解密没有影响 **/
void sqlite3_activate_see(const char* right )
{
return;
}
int sqlite3_key(sqlite3 *db,int nKey);
int sqlite3_rekey(sqlite3 *db,int nKey);
/*** 下面是上面的函数的辅助处理函数 ***/
// 从用户提供的缓冲区中得到一个加密密钥
// 用户提供的密钥可能位数上满足不了要求,使用这个函数来完成密钥扩展
static unsigned char * DeriveKey(const void *pKey,int nKeyLen);
//创建或更新一个页的加密算法索引.此函数会申请缓冲区.
static LPCryptBlock CreateCryptBlock(unsigned char* hKey,Pager *pager,LPCryptBlock pExisting);
//加密/解密函数,被pager调用
void * sqlite3Codec(void *pArg,unsigned char *data,Pgno nPageNum,int nMode);
//设置密码函数
int __stdcall sqlite3_key_interop(sqlite3 *db,int nKeySize);
// 修改密码函数
int __stdcall sqlite3_rekey_interop(sqlite3 *db,int nKeySize);
//销毁一个加密块及相关的缓冲区,密钥.
static void DestroyCryptBlock(LPCryptBlock pBlock);
static void * sqlite3pager_get_codecarg(Pager *pPager);
void sqlite3pager_set_codec(Pager *pPager,void *(*xCodec)(void*,Pgno,int),void *pCodecArg );
//加密/解密函数,int nMode)
{
LPCryptBlock pBlock = (LPCryptBlock)pArg;
unsigned int dwPageSize = 0;
if (!pBlock) return data;
// 确保pager的页长度和加密块的页长度相等.如果改变,就需要调整.
if (nMode != 2)
{
PgHdr *pageHeader;
pageHeader = DATA_TO_PGHDR(data);
if (pageHeader->pPager->pageSize != pBlock->PageSize)
{
CreateCryptBlock(0,pageHeader->pPager,pBlock);
}
}
switch(nMode)
{
case 0: // Undo a "case 7" journal file encryption
case 2: //重载一个页
case 3: //载入一个页
if (!pBlock->ReadKey) break;
dwPageSize = pBlock->PageSize;
My_DeEncrypt_Func(data,dwPageSize,pBlock->ReadKey,DB_KEY_LENGTH_BYTE ); /*调用我的解密函数*/
break;
case 6: //加密一个主数据库文件的页
if (!pBlock->WriteKey) break;
memcpy(pBlock->Data + CRYPT_OFFSET,data,pBlock->PageSize);
data = pBlock->Data + CRYPT_OFFSET;
dwPageSize = pBlock->PageSize;
My_Encrypt_Func(data,pBlock->WriteKey,DB_KEY_LENGTH_BYTE ); /*调用我的加密函数*/
break;
case 7: //加密事务文件的页
/*在正常环境下,读密钥和写密钥相同. 当数据库是被重新加密的,读密钥和写密钥未必相同. 回滚事务必要用数据库文件的原始密钥写入.因此,当一次回滚被写入,总是用数据库的读密钥,这是为了保证与读取原始数据的密钥相同. */
if (!pBlock->ReadKey) break;
memcpy(pBlock->Data + CRYPT_OFFSET,pBlock->PageSize);
data = pBlock->Data + CRYPT_OFFSET;
dwPageSize = pBlock->PageSize;
My_Encrypt_Func( data,DB_KEY_LENGTH_BYTE ); /*调用我的加密函数*/
break;
}
return data;
}
//销毁一个加密块及相关的缓冲区,密钥.
static void DestroyCryptBlock(LPCryptBlock pBlock)
{
//销毁读密钥.
if (pBlock->ReadKey){
sqliteFree(pBlock->ReadKey);
}
//如果写密钥存在并且不等于读密钥,也销毁.
if (pBlock->WriteKey && pBlock->WriteKey != pBlock->ReadKey){
sqliteFree(pBlock->WriteKey);
}
if(pBlock->Data){
sqliteFree(pBlock->Data);
}
//释放加密块.
sqliteFree(pBlock);
}
static void * sqlite3pager_get_codecarg(Pager *pPager)
{
return (pPager->xCodec) ? pPager->pCodecArg: NULL;
}
// 从用户提供的缓冲区中得到一个加密密钥
static unsigned char * DeriveKey(const void *pKey,int nKeyLen)
{
unsigned char * hKey = NULL;
int j;
if( pKey == NULL || nKeyLen == 0 )
{
return NULL;
}
hKey = sqliteMalloc( DB_KEY_LENGTH_BYTE + 1 );
if( hKey == NULL )
{
return NULL;
}
hKey[ DB_KEY_LENGTH_BYTE ] = 0;
if( nKeyLen < DB_KEY_LENGTH_BYTE )
{
memcpy( hKey,pKey,nKeyLen ); //先拷贝得到密钥前面的部分
j = DB_KEY_LENGTH_BYTE - nKeyLen;
//补充密钥后面的部分
memset( hKey + nKeyLen,DB_KEY_PADDING,j );
}
else
{ //密钥位数已经足够,直接把密钥取过来
memcpy( hKey,DB_KEY_LENGTH_BYTE );
}
return hKey;
}
//创建或更新一个页的加密算法索引.此函数会申请缓冲区.
static LPCryptBlock CreateCryptBlock(unsigned char* hKey,LPCryptBlock pExisting)
{
LPCryptBlock pBlock;
if (!pExisting) //创建新加密块
{
pBlock = sqliteMalloc(sizeof(CryptBlock));
memset(pBlock,0,sizeof(CryptBlock));
pBlock->ReadKey = hKey;
pBlock->WriteKey = hKey;
pBlock->PageSize = pager->pageSize;
pBlock->Data = (unsigned char*)sqliteMalloc(pBlock->PageSize + CRYPT_OFFSET);
}
else //更新存在的加密块
{
pBlock = pExisting;
if ( pBlock->PageSize != pager->pageSize && !pBlock->Data){
sqliteFree(pBlock->Data);
pBlock->PageSize = pager->pageSize;
pBlock->Data = (unsigned char*)sqliteMalloc(pBlock->PageSize + CRYPT_OFFSET);
}
}
memset(pBlock->Data,pBlock->PageSize + CRYPT_OFFSET);
return pBlock;
}
/* ** Set the codec for this pager */
void sqlite3pager_set_codec(
Pager *pPager,void *pCodecArg
)
{
pPager->xCodec = xCodec;
pPager->pCodecArg = pCodecArg;
}
int sqlite3_key(sqlite3 *db,int nKey)
{
return sqlite3_key_interop(db,nKey);
}
int sqlite3_rekey(sqlite3 *db,int nKey)
{
return sqlite3_rekey_interop(db,nKey);
}
/*被sqlite 和 sqlite3_key_interop 调用,int nKeyLen)
{
int rc = SQLITE_ERROR;
unsigned char* hKey = 0;
//如果没有指定密匙,可能标识用了主数据库的加密或没加密.
if (!pKey || !nKeyLen)
{
if (!nDb)
{
return SQLITE_OK; //主数据库,没有指定密钥所以没有加密.
}
else //附加数据库,使用主数据库的密钥.
{
//获取主数据库的加密块并复制密钥给附加数据库使用
LPCryptBlock pBlock = (LPCryptBlock)sqlite3pager_get_codecarg(sqlite3BtreePager(db->aDb[0].pBt));
if (!pBlock) return SQLITE_OK; //主数据库没有加密
if (!pBlock->ReadKey) return SQLITE_OK; //没有加密
memcpy(pBlock->ReadKey,&hKey,16);
}
}
else //用户提供了密码,从中创建密钥.
{
hKey = DeriveKey(pKey,nKeyLen);
}
//创建一个新的加密块,并将解码器指向新的附加数据库.
if (hKey)
{
LPCryptBlock pBlock = CreateCryptBlock(hKey,sqlite3BtreePager(db->aDb[nDb].pBt),NULL);
sqlite3pager_set_codec(sqlite3BtreePager(db->aDb[nDb].pBt),sqlite3Codec,pBlock);
rc = SQLITE_OK;
}
return rc;
}
// Changes the encryption key for an existing database.
int __stdcall sqlite3_rekey_interop(sqlite3 *db,int nKeySize)
{
Btree *pbt = db->aDb[0].pBt;
Pager *p = sqlite3BtreePager(pbt);
LPCryptBlock pBlock = (LPCryptBlock)sqlite3pager_get_codecarg(p);
unsigned char * hKey = DeriveKey(pKey,nKeySize);
int rc = SQLITE_ERROR;
if (!pBlock && !hKey) return SQLITE_OK;
//重新加密一个数据库,改变pager的写密钥,读密钥依旧保留.
if (!pBlock) //加密一个未加密的数据库
{
pBlock = CreateCryptBlock(hKey,p,NULL);
pBlock->ReadKey = 0; // 原始数据库未加密
sqlite3pager_set_codec(sqlite3BtreePager(pbt),pBlock);
}
else // 改变已加密数据库的写密钥
{
pBlock->WriteKey = hKey;
}
// 开始一个事务
rc = sqlite3BtreeBeginTrans(pbt,1);
if (!rc)
{
// 用新密钥重写所有的页到数据库。
Pgno nPage = sqlite3PagerPagecount(p);
Pgno nSkip = PAGER_MJ_PGNO(p);
void *pPage;
Pgno n;
for(n = 1; rc == SQLITE_OK && n <= nPage; n ++)
{
if (n == nSkip) continue;
rc = sqlite3PagerGet(p,n,&pPage);
if(!rc)
{
rc = sqlite3PagerWrite(pPage);
sqlite3PagerUnref(pPage);
}
}
}
// 如果成功,提交事务。
if (!rc)
{
rc = sqlite3BtreeCommit(pbt);
}
// 如果失败,回滚。
if (rc)
{
sqlite3BtreeRollback(pbt);
}
// 如果成功,销毁先前的读密钥。并使读密钥等于当前的写密钥。
if (!rc)
{
if (pBlock->ReadKey)
{
sqliteFree(pBlock->ReadKey);
}
pBlock->ReadKey = pBlock->WriteKey;
}
else// 如果失败,销毁当前的写密钥,并恢复为当前的读密钥。
{
if (pBlock->WriteKey)
{
sqliteFree(pBlock->WriteKey);
}
pBlock->WriteKey = pBlock->ReadKey;
}
// 如果读密钥和写密钥皆为空,就不需要再对页进行编解码。
// 销毁加密块并移除页的编解码器
if (!pBlock->ReadKey && !pBlock->WriteKey)
{
sqlite3pager_set_codec(p,NULL);
DestroyCryptBlock(pBlock);
}
return rc;
}
/*** 下面是加密函数的主体 ***/
int __stdcall sqlite3_key_interop(sqlite3 *db,int nKeySize)
{
return sqlite3CodecAttach(db,nKeySize);
}
// 释放与一个页相关的加密块
void sqlite3pager_free_codecarg(void *pArg)
{
if (pArg)
DestroyCryptBlock((LPCryptBlock)pArg);
}
#endif //#ifdef SQLITE_HAS_CODEC
五、性能优化 PRAGMA temp_store;
PRAGMA temp_store = DEFAULT; (0)
PRAGMA temp_store = FILE; (1)
PRAGMA temp_store = MEMORY; (2)
查询或更改”temp_store”参数的设置。当temp_store设置为DEFAULT (0),使用编译时的C预处理宏 TEMP_STORE来定义储存临时表和临时索引的位置。当设置为MEMORY (2)临时表和索引存放于内存中。 当设置为FILE (1)则存放于文件中。temp_store_directorypragma 可用于指定存放该文件的目录。当改变temp_store设置,所有已存在的临时表,索引,触发器及视图将被立即删除。 六、后记 本文转载自:http://www.52php.cn/article/p-opnaqgbk-vu.html(董淳光)。重点内容 (补充后记) 本文在原文基础上增加了:C/C++开发接口简介和性能优化两节,并对原作者的排版作了调整。本文同样可以随意的转载、修改和引用,但必须遵守原作者的意愿。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |