SQLite学习教程学习总结_第1页
SQLite学习教程学习总结_第2页
SQLite学习教程学习总结_第3页
SQLite学习教程学习总结_第4页
SQLite学习教程学习总结_第5页
已阅读5页,还剩36页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

SQLite学习教程1:sqlite常用接口2个重要结构体和5个主要函数:sqlite3

*pdb,数据库句柄,跟文件句柄FILE很类似sqlite3_stmt

*stmt,这个相当于ODBC的Command对象,用于保存编译好的SQL语句

sqlite3_open(),

打开数据库sqlite3_exec(),

执行非查询的sql语句sqlite3_prepare(),准备sql语句,执行select语句或者要使用parameterbind时,用这个函数(封装了sqlite3_exec).Sqlite3_step(),在调用sqlite3_prepare后,使用这个函数在记录集中移动。Sqlite3_close(),关闭数据库文件

还有一系列的函数,用于从记录集字段中获取数据,如sqlite3_column_text(),取text类型的数据。sqlite3_column_blob(),取blob类型的数据sqlite3_column_int(),取int类型的数据…

2:sqlite数据类型介绍

在进行数据库Sql操作之前,首先有个问题需要说明,就是Sqlite的数据类型,和其他的数据库不同,Sqlite支持的数据类型有他自己的特色,这个特色有时会被认为是一个潜在的缺点,但是这个问题并不在我们的讨论范围之内。大多数的数据库在数据类型上都有严格的限制,在建立表的时候,每一列都必须制定一个数据类型,只有符合该数据类型的数据可以被保存在这一列当中。而在Sqlite2.X中,数据类型这个属性只属于数据本生,而不和数据被存在哪一列有关,也就是说数据的类型并不受数据列限制(有一个例外:INTEGERPRIMARYKEY,该列只能存整型数据)。但是当Sqlite进入到3.0版本的时候,这个问题似乎又有了新的答案,Sqlite的开发者开始限制这种无类型的使用,在3.0版本当中,每一列开始拥有自己的类型,并且在数据存入该列的时候,数据库会试图把数据的类型向该类型转换,然后以转换之后的类型存储。当然,如果转换被认为是不可行的,Sqlite仍然会存储这个数据,就像他的前任版本一样。举个例子,如果你企图向一个INTEGER类型的列中插入一个字符串,Sqlite会检查这个字符串是否有整型数据的特征,如果有而且可以被数据库所识别,那么该字符串会被转换成整型再保存,如果不行,则还是作为整型存储。总的来说,所有存在Sqlite3.0版本当中的数据都拥有以下之一的数据类型:空(NULL):该值为空整型(INTEGEER):有符号整数,按大小被存储成1,2,3,4,6或8字节。实数(REAL):浮点数,以8字节指数形式存储。文本(TEXT):字符串,以数据库编码方式存储(UTF-8,UTF-16BE或者UTF-16-LE)。BLOB:BLOB数据不做任何转换,以输入形式存储。ps:在关系数据库中,CLOB和BLOB类型被用来存放大对象。BOLB表示二进制大对象,这种数据类型通过用来保存图片,图象,视频等。CLOB表示字符大对象,能够存放大量基于字符的数据。对应的,对于数据列,同样有以下的数据类型:TEXTNUMERICINTEGERREALNONE数据列的属性的作用是确定对插入的数据的转换方向:TEXT将数据向文本进行转换,对应的数据类型为NULL,TEXT或BLOBNUMERIC将数据向数字进行转换,对应的数据类型可能为所有的五类数据,当试图存入文本时将执行向整型或浮点类型的转换(视具体的数值而定),转换若不可行,则保留文本类型存储,NULL或BLOB不做变化INTEGER将数据向整型转换,类似于NUMERIC,不同的是没有浮点标志的浮点数将转换为整型保存REAL将数据向浮点数类型转换,类似于NUMERIC,不同的是整数将转换为浮点数保存NULL不做任何转换的数据列类型

实例代码如下,附件工程可直接编译,例子使用了blob数据类型。#include"sqlite3.h"

//包含一个头文件就可以使用所以sqlite的接口了#include"stdlib.h"#include"stdio.h"#include"string.h"

#pragmacomment(lib,"sqlite.lib")

//我把sqlite编译成了一个静态的lib文件。

void

createdb();void

querydb();

int

main(){

createdb();

querydb();

return0;}

void

createdb(){

int

ret;

sqlite3

*pdb=0;

sqlite3_stmt

*stmt=0;

char

*error=0;

char

*sql="insertintotable1values('value11',:aaa)";

int

index;

staticvoid

*value="asdfadsfasdfjasdfjaksdfaskjdfakdsfaksfja";

ret=sqlite3_open("db1.sdb",&pdb);

//打开数据库,跟打开文本文件一样

if(ret!=SQLITE_OK)

return;

ret=sqlite3_exec(pdb,"createtabletable1(col1char(20),col2BLOB)",0,0,&error);

if(ret!=SQLITE_OK)

return;

ret=sqlite3_prepare(pdb,sql,strlen(sql),&stmt,&error);

if(ret!=SQLITE_OK)

return;

index=sqlite3_bind_parameter_index(stmt,":aaa");

ret=sqlite3_bind_blob(stmt,index,value,strlen(value),SQLITE_STATIC);

if(ret!=SQLITE_OK)

return;

ret=sqlite3_step(stmt);

if(ret!=SQLITE_DONE)

return;

sqlite3_close(pdb);

}

void

querydb(){

int

ret;

sqlite3

*pdb=0;

sqlite3_stmt

*pstmt=0;

char

*error=0;

char

*sql="select*fromtable1";

int

len;

int

i;

char

*name;

void

*value;

ret=sqlite3_open("db1.sdb",&pdb);

if(ret!=SQLITE_OK)

return;

ret=sqlite3_prepare(pdb,sql,strlen(sql),&pstmt,&error);

if(ret!=SQLITE_OK)

return;

while(1)

{

ret=sqlite3_step(pstmt);

if(ret!=SQLITE_ROW)

break;

name=sqlite3_column_text(pstmt,0);

value=sqlite3_column_blob(pstmt,1);

len=sqlite3_column_bytes(pstmt,1);

}}

实例二:SQLite中如何用api操作blob类型的字段

在实际的编程开发当中我们经常要处理一些大容量二进制数据的存储,如图片或者音乐等等。对于这些二进制数据(blob字段)我们不能像处理普通的文本那样简单的插入或者查询,为此SQLite提供了一组函数来处理这种BLOB字段类型。下面的代码演示了如何使用这些API函数。

首先我们要建立一个数据库:sqlite3_exec(db,"CREATETABLElist(flienamevarchar(128)UNIQUE,fzipblob);",0,0,&zErrMsg);

//由于mmmm.rar是一个二进制文件,所以要在使用insert语句时先用?号代替

sqlite3_prepare(db,"insertintolistvalues('mmmm.rar',?);",-1,&stat,0);

FILE*fp;

longfilesize=0;

char*ffile;

fp=fopen("mmmm.rar","rb");

if(fp!=NULL)

{

//计算文件的大小

fseek(fp,0,SEEK_END);

filesize=ftell(fp);

fseek(fp,0,SEEK_SET);

//读取文件

ffile=newchar[filesize+1];

size_tsz=fread(ffile,sizeof(char),filesize+1,fp);

fclose(fp);

}

//将文件数据绑定到insert语句中,替换“?”部分

sqlite3_bind_blob(stat,1,ffile,filesize,NULL);

//执行绑定之后的SQL语句

sqlite3_step(stat);这时数据库当中已经有了一条包含BLOB字段的数据。接下来我们要读取这条数据:

//选取该条数据

sqlite3_prepare(db,"select*fromlist;",-1,&stat,0);

sqlite3_step(stat);//得到纪录中的BLOB字段constvoid*test=sqlite3_column_blob(stat,1);//得到字段中数据的长度

intsize=sqlite3_column_bytes(stat,1);

//拷贝该字段

sprintf(buffer2,"%s",test);此时可以将buffer2写入到文件当中,至此BLOB数据处理完毕。

实例三:sqlite中用blob存储图片和取出图片

#include<iostream>#include<string>#include<sqlite3.h>usingnamespacestd;intmain(){

sqlite3*db;

sqlite3_stmt*stat;

char*zErrMsg=0;

charbuffer2[1024]="0";

sqlite3_open("./MetaInfo.db",&db);

intresult;

if(result)

{

cout<<"Openthedatabasesqlite.dbfailed"<<endl;

}

else

cout<<"Openthedatabasesqlite.dbsucessfully"<<endl;

sqlite3_exec(db,"CREATETABLElist(flienamevarchar(128)UNIQUE,fzipblob);",0,0,&zErrMsg);

sqlite3_prepare(db,"insertintolistvalues('./data/2.bmp',?);",-1,&stat,0);

FILE*fp;

longfilesize=0;

char*ffile;

fp=fopen("./data/2.bmp","rb");

if(fp!=NULL)

{

fseek(fp,0,SEEK_END);

filesize=ftell(fp);

fseek(fp,0,SEEK_SET);

ffile=newchar[filesize+1];

size_tsz=fread(ffile,sizeof(char),filesize+1,fp);

fclose(fp);

}

sqlite3_bind_blob(stat,1,ffile,filesize,NULL);

sqlite3_step(stat);

sqlite3_prepare(db,"select*fromlist;",-1,&stat,0);

sqlite3_step(stat);

constvoid*test=sqlite3_column_blob(stat,1);

intsize=sqlite3_column_bytes(stat,1);

sprintf(buffer2,"%s",test);

FILE*fp2;

fp2=fopen("outfile.png","wb");

if(fp2!=NULL)

{

size_tret=fwrite(test,sizeof(char),size,fp2);

fclose(fp2);

}

delete(ffile);

sqlite3_finalize(stat);

sqlite3_close(db);

return0;}

SQLite3是SQLite一个全新的版本,它虽然是在SQLite2.8.13的代码基础之上开发的,但是使用了和之前的版本不兼容的数据库格式和API.SQLite3是为了满足以下的需求而开发的:支持UTF-16编码.用户自定义的文本排序方法.可以对BLOBs字段建立索引.因此为了支持这些特性我改变了数据库的格式,建立了一个与之前版本不兼容的3.0版.至于其他的兼容性的改变,例如全新的API等等,都将在理论介绍之后向你说明,这样可以使你最快的一次性摆脱兼容性问题.3.0版的和2.X版的API非常相似,但是有一些重要的改变需要注意.所有API接口函数和数据结构的前缀都由"sqlite_"改为了"sqlite3_".这是为了避免同时使用SQLite2.X和SQLite3.0这两个版本的时候发生链接冲突.由于对于C语言应该用什么数据类型来存放UTF-16编码的字符串并没有一致的规范.因此SQLite使用了普通的void*类型来指向UTF-16编码的字符串.客户端使用过程中可以把void*映射成适合他们的系统的任何数据类型.2.0C/C++接口SQLite3.0一共有83个API函数,此外还有一些数据结构和预定义(#defines).(完整的API介绍请参看另一份文档.)不过你们可以放心,这些接口使用起来不会像它的数量所暗示的那么复杂.最简单的程序仍然使用三个函数就可以完成:sqlite3_open(),sqlite3_exec(),和sqlite3_close().要是想更好的控制数据库引擎的执行,可以使用提供的sqlite3_prepare()函数把SQL语句编译成字节码,然后在使用sqlite3_step()函数来执行编译后的字节码.以sqlite3_column_开头的一组API函数用来获取查询结果集中的信息.许多接口函数都是成对出现的,同时有UTF-8和UTF-16两个版本.并且提供了一组函数用来执行用户自定义的SQL函数和文本排序函数.2.1如何打开关闭数据库

typedefstructsqlite3sqlite3;

intsqlite3_open(constchar*,sqlite3**);

intsqlite3_open16(constvoid*,sqlite3**);

intsqlite3_close(sqlite3*);

constchar*sqlite3_errmsg(sqlite3*);

constvoid*sqlite3_errmsg16(sqlite3*);

intsqlite3_errcode(sqlite3*);sqlite3_open()函数返回一个整数错误代码,而不是像第二版中一样返回一个指向sqlite3结构体的指针.sqlite3_open()和sqlite3_open16()的不同之处在于sqlite3_open16()使用UTF-16编码(使用本地主机字节顺序)传递数据库文件名.如果要创建新数据库,sqlite3_open16()将内部文本转换为UTF-16编码,反之sqlite3_open()将文本转换为UTF-8编码.打开或者创建数据库的命令会被缓存,直到这个数据库真正被调用的时候才会被执行.而且允许使用PRAGMA声明来设置如本地文本编码或默认内存页面大小等选项和参数.sqlite3_errcode()通常用来获取最近调用的API接口返回的错误代码.sqlite3_errmsg()则用来得到这些错误代码所对应的文字说明.这些错误信息将以UTF-8的编码返回,并且在下一次调用任何SQLiteAPI函数的时候被清除.sqlite3_errmsg16()和sqlite3_errmsg()大体上相同,除了返回的错误信息将以UTF-16本机字节顺序编码.SQLite3的错误代码相比SQLite2没有任何的改变,它们分别是:#defineSQLITE_OK

0

#defineSQLITE_ERROR

1

#defineSQLITE_INTERNAL

2

#defineSQLITE_PERM

3

#defineSQLITE_ABORT

4

#defineSQLITE_BUSY

5

#defineSQLITE_LOCKED

6

#defineSQLITE_NOMEM

7

#defineSQLITE_READONLY

8

#defineSQLITE_INTERRUPT

9

#defineSQLITE_IOERR

10

#defineSQLITE_CORRUPT

11

#defineSQLITE_NOTFOUND

12

#defineSQLITE_FULL

13

#defineSQLITE_CANTOPEN

14

#defineSQLITE_PROTOCOL

15

#defineSQLITE_EMPTY

16

#defineSQLITE_SCHEMA

17

#defineSQLITE_TOOBIG

18

#defineSQLITE_CONSTRAINT

19

#defineSQLITE_MISMATCH

20

#defineSQLITE_MISUSE

21

#defineSQLITE_NOLFS

22

#defineSQLITE_AUTH

23

#defineSQLITE_ROW

100

#defineSQLITE_DONE

101

2.2执行SQL语句

typedefint(*sqlite_callback)(void*,int,char**,char**);

intsqlite3_exec(sqlite3*,constchar*sql,sqlite_callback,void*,char**);sqlite3_exec函数依然像它在SQLite2中一样承担着很多的工作.该函数的第二个参数中可以编译和执行零个或多个SQL语句.查询的结果返回给回调函数.更多地信息可以查看API参考.在SQLite3里,sqlite3_exec一般是被准备SQL语句接口封装起来使用的.

typedefstructsqlite3_stmtsqlite3_stmt;

intsqlite3_prepare(sqlite3*,constchar*,int,sqlite3_stmt**,constchar**);

intsqlite3_prepare16(sqlite3*,constvoid*,int,sqlite3_stmt**,constvoid**);

intsqlite3_finalize(sqlite3_stmt*);

intsqlite3_reset(sqlite3_stmt*);sqlite3_prepare接口把一条SQL语句编译成字节码留给后面的执行函数.使用该接口访问数据库是当前比较好的的一种方法.sqlite3_prepare()处理的SQL语句应该是UTF-8编码的.而sqlite3_prepare16()则要求是UTF-16编码的.输入的参数中只有第一个SQL语句会被编译.第四个参数则用来指向输入参数中下一个需要编译的SQL语句存放的SQLitestatement对象的指针,任何时候如果调用sqlite3_finalize()将销毁一个准备好的SQL声明.在数据库关闭之前,所有准备好的声明都必须被释放销毁.sqlite3_reset()函数用来重置一个SQL声明的状态,使得它可以被再次执行.SQL声明可以包含一些型如"?"或"?nnn"或":aaa"的标记,其中"nnn"是一个整数,"aaa"是一个字符串.这些标记代表一些不确定的字符值(或者说是通配符),可以在后面用sqlite3_bind接口来填充这些值.每一个通配符都被分配了一个编号(由它在SQL声明中的位置决定,从1开始),此外也可以用"nnn"来表示"?nnn"这种情况.允许相同的通配符在同一个SQL声明中出现多次,在这种情况下所有相同的通配符都会被替换成相同的值.没有被绑定的通配符将自动取NULL值.

intsqlite3_bind_blob(sqlite3_stmt*,int,constvoid*,intn,void(*)(void*));

intsqlite3_bind_double(sqlite3_stmt*,int,double);

intsqlite3_bind_int(sqlite3_stmt*,int,int);

intsqlite3_bind_int64(sqlite3_stmt*,int,longlongint);

intsqlite3_bind_null(sqlite3_stmt*,int);

intsqlite3_bind_text(sqlite3_stmt*,int,constchar*,intn,void(*)(void*));

intsqlite3_bind_text16(sqlite3_stmt*,int,constvoid*,intn,void(*)(void*));

intsqlite3_bind_value(sqlite3_stmt*,int,constsqlite3_value*);以上是sqlite3_bind所包含的全部接口,它们是用来给SQL声明中的通配符赋值的.没有绑定的通配符则被认为是空值.绑定上的值不会被sqlite3_reset()函数重置.但是在调用了sqlite3_reset()之后所有的通配符都可以被重新赋值.在SQL声明准备好之后(其中绑定的步骤是可选的),需要调用以下的方法来执行:

intsqlite3_step(sqlite3_stmt*);如果SQL返回了一个单行结果集,sqlite3_step()函数将返回SQLITE_ROW,如果SQL语句执行成功或者正常将返回SQLITE_DONE,否则将返回错误代码.如果不能打开数据库文件则会返回SQLITE_BUSY.如果函数的返回值是SQLITE_ROW,那么下边的这些方法可以用来获得记录集行中的数据:

constvoid*sqlite3_column_blob(sqlite3_stmt*,intiCol);

intsqlite3_column_bytes(sqlite3_stmt*,intiCol);

intsqlite3_column_bytes16(sqlite3_stmt*,intiCol);

intsqlite3_column_count(sqlite3_stmt*);

constchar*sqlite3_column_decltype(sqlite3_stmt*,intiCol);

constvoid*sqlite3_column_decltype16(sqlite3_stmt*,intiCol);

doublesqlite3_column_double(sqlite3_stmt*,intiCol);

intsqlite3_column_int(sqlite3_stmt*,intiCol);

longlongintsqlite3_column_int64(sqlite3_stmt*,intiCol);

constchar*sqlite3_column_name(sqlite3_stmt*,intiCol);

constvoid*sqlite3_column_name16(sqlite3_stmt*,intiCol);

constunsignedchar*sqlite3_column_text(sqlite3_stmt*,intiCol);

constvoid*sqlite3_column_text16(sqlite3_stmt*,intiCol);

intsqlite3_column_type(sqlite3_stmt*,intiCol);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()仍然会返回结果集中包含的列数.返回的记录集通过使用其它的几个sqlite3_column_***()函数来提取,所有的这些函数都把列的编号作为第二个参数.列编号从左到右以零起始.请注意它和之前那些从1起始的参数的不同.sqlite3_column_type()函数返回第N列的值的数据类型.具体的返回值如下:

#defineSQLITE_INTEGER

1

#defineSQLITE_FLOAT

2

#defineSQLITE_TEXT

3

#defineSQLITE_BLOB

4

#defineSQLITE_NULL

5sqlite3_column_decltype()则用来返回该列在CREATETABLE语句中声明的类型.它可以用在当返回类型是空字符串的时候.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()返回浮点数.不一定非要按照sqlite3_column_type()接口返回的数据类型来获取数据.数据类型不同时软件将自动转换.DatatypesInSQLiteVersion31.StorageClassesVersion2ofSQLitestoresallcolumnvaluesasASCIItext.Version3enhancesthisbyprovidingtheabilitytostoreintegerandrealnumbersinamorecompactformatandthecapabilitytostoreBLOBdata.EachvaluestoredinanSQLitedatabase(ormanipulatedbythedatabaseengine)hasoneofthefollowingstorageclasses:NULL.ThevalueisaNULLvalue.INTEGER.Thevalueisasignedinteger,storedin1,2,3,4,6,or8bytesdependingonthemagnitudeofthevalue.REAL.Thevalueisafloatingpointvalue,storedasan8-byteIEEEfloatingpointnumber.TEXT.Thevalueisatextstring,storedusingthedatabaseencoding(UTF-8,UTF-16BEorUTF-16-LE).BLOB.Thevalueisablobofdata,storedexactlyasitwasinput.AsinSQLiteversion2,anycolumninaversion3databaseexceptanINTEGERPRIMARYKEYmaybeusedtostoreanytypeofvalue.Theexceptiontothisruleisdescribedbelowunder'StrictAffinityMode'.AllvaluessuppliedtoSQLite,whetherasliteralsembeddedinSQLstatementsorvaluesboundtopre-compiledSQLstatementsareassignedastorageclassbeforetheSQLstatementisexecuted.Undercircumstancesdescribedbelow,thedatabaseenginemayconvertvaluesbetweennumericstorageclasses(INTEGERandREAL)andTEXTduringqueryexecution.Storageclassesareinitiallyassignedasfollows:ValuesspecifiedasliteralsaspartofSQLstatementsareassignedstorageclassTEXTiftheyareenclosedbysingleordoublequotes,INTEGERiftheliteralisspecifiedasanunquotednumberwithnodecimalpointorexponent,REALiftheliteralisanunquotednumberwithadecimalpointorexponentandNULLifthevalueisaNULL.LiteralswithstorageclassBLOBarespecifiedusingtheX'ABCD'notation.Valuessuppliedusingthesqlite3_bind_*APIsareassignedthestorageclassthatmostcloselymatchesthenativetypebound(i.e.sqlite3_bind_blob()bindsavaluewithstorageclassBLOB).ThestorageclassofavaluethatistheresultofanSQLscalaroperatordependsontheoutermostoperatoroftheexpression.User-definedfunctionsmayreturnvalueswithanystorageclass.Itisnotgenerallypossibletodeterminethestorageclassoftheresultofanexpressionatcompiletime.2.ColumnAffinityInSQLiteversion3,thetypeofavalueisassociatedwiththevalueitself,notwiththecolumnorvariableinwhichthevalueisstored.(Thisissometimescalledmanifesttyping.)AllotherSQLdatabasesenginesthatweareawareofusethemorerestrictivesystemofstatictypingwherethetypeisassociatedwiththecontainer,notthevalue.InordertomaximizecompatibilitybetweenSQLiteandotherdatabaseengines,SQLitesupporttheconceptof"typeaffinity"oncolumns.Thetypeaffinityofacolumnistherecommendedtypefordatastoredinthatcolumn.Thekeyhereisthatthetypeisrecommended,notrequired.Anycolumncanstillstoreanytypeofdata,intheory.Itisjustthatsomecolumns,giventhechoice,willprefertouseonestorageclassoveranother.Thepreferredstorageclassforacolumniscalledits"affinity".EachcolumninanSQLite3databaseisassignedoneofthefollowingtypeaffinities:TEXTNUMERICINTEGERREALNONEAcolumnwithTEXTaffinitystoresalldatausingstorageclassesNULL,TEXTorBLOB.IfnumericaldataisinsertedintoacolumnwithTEXTaffinityitisconvertedtotextformbeforebeingstored.AcolumnwithNUMERICaffinitymaycontainvaluesusingallfivestorageclasses.WhentextdataisinsertedintoaNUMERICcolumn,anattemptismadetoconvertittoanintegerorrealnumberbeforeitisstored.Iftheconversionissuccessful,thenthevalueisstoredusingtheINTEGERorREALstorageclass.IftheconversioncannotbeperformedthevalueisstoredusingtheTEXTstorageclass.NoattemptismadetoconvertNULLorblobvalues.AcolumnthatusesINTEGERaffinitybehavesinthesamewayasacolumnwithNUMERICaffinity,exceptthatifarealvaluewithnofloatingpointcomponent(ortextvaluethatconvertstosuch)isinserteditisconvertedtoanintegerandstoredusingtheINTEGERstorageclass.AcolumnwithREALaffinitybehaveslikeacolumnwithNUMERICaffinityexceptthatitforcesintegervaluesintofloatingpointrepresentation.(Asanoptimization,integervaluesarestoredondiskasintegersinordertotakeuplessspaceandareonlyconvertedtofloatingpointasthevalueisreadoutofthetable.)AcolumnwithaffinityNONEdoesnotpreferonestorageclassoveranother.Itmakesnoattempttocoercedatabeforeitisinserted.2.1DeterminationOfColumnAffinityThetypeaffinityofacolumnisdeterminedbythedeclaredtypeofthecolumn,accordingtothefollowingrules:Ifthedatatypecontainsthestring"INT"thenitisassignedINTEGERaffinity.Ifthedatatypeofthecolumncontainsanyofthestrings"CHAR","CLOB",or"TEXT"thenthatcolumnhasTEXTaffinity.NoticethatthetypeVARCHARcontainsthestring"CHAR"andisthusassignedTEXTaffinity.Ifthedatatypeforacolumncontainsthestring"BLOB"orifnodatatypeisspecifiedthenthecolumnhasaffinityNONE.Ifthedatatypeforacolumncontainsanyofthestrings"REAL","FLOA",or"DOUB"thenthecolumnhasREALaffinityOtherwise,theaffinityisNUMERIC.Ifatableiscreatedusinga"CREATETABLE<table>ASSELECT..."statement,thenallcolumnshavenodatatypespecifiedandtheyaregivennoaffinity.2.2ColumnAffinityExampleCREATETABLEt1(

t

TEXT,

nuNUMERIC,

i

INTEGER,

noBLOB);--Storageclassesforthefollowingrow:--TEXT,REAL,INTEGER,TEXTINSERTINTOt1VALUES('500.0','500.0','500.0','500.0');--Storageclassesforthefollowingrow:--TEXT,REAL,INTEGER,REALINSERTINTOt1VALUES(500.0,500.0,500.0,500.0);3.ComparisonExpressionsLikeSQLiteversion2,version3featuresthebinarycomparisonoperators'=','<','<=','>='and'!=',anoperationtotestforsetmembership,'IN',andtheternarycomparisonoperator'BETWEEN'.Theresultsofacomparisondependonthestorageclassesofthetwovaluesbeingcompared,accordingtothefollowingrules:AvaluewithstorageclassNULLisconsideredlessthananyothervalue(includinganothervaluewithstorageclassNULL).AnINTEGERorREALvalueislessthananyTEXTorBLOBvalue.WhenanINTEGERorREALiscomparedtoanotherINTEGERorREAL,anumericalcomparisonisperformed.ATEXTvalueislessthanaBLOBvalue.WhentwoTEXTvaluesarecompared,theClibraryfunctionmemcmp()isusuallyusedtodeterminetheresult.Howeverthiscanbeoverridden,asdescribedunder'User-definedcollationSequences'below.WhentwoBLOBvaluesarecompared,theresultisalwaysdeterminedusingmemcmp().SQLitemayattempttoconvertvaluesbetweenthenumericstorageclasses(INTEGERandREAL)andTEXTbeforeperformingacomparison.Forbinarycomparisons,thisisdoneinthecasesenumeratedbelow.Theterm"expression"usedinthebulletpointsbelowmeansanySQLscalarexpressionorliteralotherthanacolumnvalue.NotethatifXandY.Zareacolumnnames,then+Xand+Y.Zareconsideredexpressions.Whenacolumnvalueiscomparedtotheresultofanexpression,theaffinityofthecolumnisappliedtotheresultoftheexpressionbeforethecomparisontakesplace.Whentwocolumnvaluesarecompared,ifonecolumnhasINTEGERorREALorNUMERICaffinityandtheotherdoesnot,thenNUMERICaffinityisappliedtoanyvalueswithstorageclassTEXTextractedfromthenon-NUMERICcolumn.Whentheresultsoftwoexpressionsarecompared,noconversionsoccur.Theresultsarecomparedasis.Ifastringiscomparedtoanumber,thenumberwillalwaysbelessthanthestring.InSQLite,theexpression"aBETWEENbANDc"isequivalentto"a>=bANDa<=c",evenifthismeansthatdifferentaffinitiesareappliedto'a'ineachofthecomparisonsrequiredtoevaluatetheexpression.Expressionsofthetype"aIN(SELECTb....)"arehandledbythethreerulesenumeratedaboveforbinarycomparisons(e.g.inasimilarmannerto"a=b").Forexampleif'b'isacolumnvalueand'a'isanexpression,thentheaffinityof'b'isappliedto'a'beforeanycomparisonstakeplace.SQLitetreatstheexpression"aIN(x,y,z)"asequivalentto"a=+xORa=+yORa=+z".ThevaluestotherightoftheINoperator(the"x","y",and"z"valuesinthisexample)areconsideredtobeexpressions,eveniftheyhappentobecolumnvalues.IfthevalueoftheleftoftheINoperatorisacolumn,thentheaffinityofthatcolumnisused.Ifthevalueisanexpressionthennoconversionsoccur.3.1ComparisonExampleCREATETABLEt1(

aTEXT,

bNUMERIC,

cBLOB);--Storageclassesforthefollowingrow:--TEXT,REAL,TEXTINSERTINTOt1VALUES('500','500','500');--60and40areconvertedto'60'and'40'andvaluesarecomparedasTEXT.SELECTa<60,a<40FROMt1;1|0--Comparisonsarenumeric.Noconversionsarerequired.SELECTb<60,b<600FROMt1;0|1--Both60and600(storageclassNUMERIC)arelessthan'500'--(storageclassTEXT).SELECTc<60,c<600FROMt1;0|04.OperatorsAllmathematicaloperators(whichistosay,alloperatorsotherthantheconcatenationoperator"||")applyNUMERICaffinitytoalloperandspriortobeingcarriedout.IfoneorbothoperandscannotbeconvertedtoNUMERICthentheresultoftheoperationisNULL.Fortheconcatenationoperator,TEXTaffinityisappliedtobothoperands.IfeitheroperandcannotbeconvertedtoTEXT(becauseitisNULLoraBLOB)thentheresultoftheconcatenationisNULL.5.Sorting,GroupingandCompoundSELECTsWhenvaluesaresortedbyanORDERbyclause,valueswithstorageclassNULLcomefirst,followedbyINTEGERandREALvaluesinterspersedinnumericorder,followedbyTEXTvaluesusuallyinmemcmp()order,andfinallyBLOBvaluesinmemcmp()order.Nostorageclassconversionsoccurbeforethesort.WhengroupingvalueswiththeGROUPBYclausevalueswithdifferentstorageclassesareconsidereddistinct,exceptforINTEGERandREALvalueswhichareconsideredequaliftheyarenumericallyequal.NoaffinitiesareappliedtoanyvaluesastheresultofaGROUPbyclause.ThecompoundSELECToperatorsUNION,INTERSECTandEXCEPTperformimplicitcomparisonsbetweenvalues.Beforethesecomparisonsareperformedanaffinitymaybeappliedtoeachvalue.Thesameaffinity,ifany,isappliedtoallvaluesthatmaybereturnedinasinglecolumnofthecompoundSELECTresultset.TheaffinityappliedistheaffinityofthecolumnreturnedbytheleftmostcomponentSELECTsthathasacolumnvalue(andnotsomeotherkindofexpression)inthatposition.IfforagivencompoundSELECTcolumnnoneofthecomponentSELECTsreturnacolumnvalue,noaffinityisappliedtothevaluesfromthatcolumnbeforetheyarecompared.6.OtherAffinityModesTheabovesectionsdescribetheoperationofthedatabaseenginein'normal'affinitymode.SQLiteversion3willfeaturetwootheraffinitymodes,asfollows:Strictaffinitymode.Inthismodeifaconversionbetweenstorageclassesiseverrequired,thedatabaseenginereturnsanerrorandthecurrentstatementisrolledback.Noaffinitymode.Inthismodenoconversionsbetweenstorageclassesareeverperformed.Comparisonsbetweenvaluesofdifferentstorageclasses(exceptforINTEGERandREAL)arealwaysfalse.7.User-definedCollationSequencesBydefault,whenSQLitecomparestwotextvalues,theresultofthecomparisonisdeterminedusingmemcmp(),regardlessoftheencodingofthestring.SQLitev3providestheabilityforuserstosupplyarbitrarycomparisonfunctions,knownasuser-defined"collationsequences"or"collatingfunctions",tobeusedinsteadofmemcmp().AsidefromthedefaultcollationsequenceBINARY,implementedusingmemcmp(),SQLitefeaturestwoextrabuilt-incollationsequencesintendedfortestingpurposes,theNOCASEandRTRIMcollations:BINARY-Comparesstringdatausingmemcmp(),regardlessoftextencoding.NOCASE-Thesameasbinary,exceptthe26uppercasecharactersofASCIIarefoldedtotheirlowercaseequivalentsbeforethecomparisonisperformed.NotethatonlyASCIIcharactersarecasefolded.SQLitedoesnotattempttoduefullUTFcasefoldingduetothesizeofthetablesrequired.RTRIM-Thesameasbinary,exceptthattrailingspacecharactersareignored.7.1AssigningCollationSequencesfromSQLEachcolumnofeachtablehasadefaultcollationtype.IfacollationtypeotherthanBINARYisrequired,aCOLLATEclauseisspecifiedaspartofthecolumndefinitiontodefineit.WhenevertwotextvaluesarecomparedbySQLite,acollationsequenceisusedtodeterminetheresultsofthecomparisonaccordingtothefollowingrules.Sections3and5ofthisdocumentdescribeth

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论