C语言SQLite3事务和锁的操作实例
本文实例讲述了C语言SQLite3事务和锁的操作。分享给大家供大家参考,具体如下:
#include#include staticintlib_get_value_callback(void*buf,intargc,char*argv[],char*column_name[]) { printf("argc:%d,%sargv[0]:%s,%sargv[1]:%s\n",argc,column_name[0],argv[0],column_name[1],argv[1]); return0; } /*! *\fnwar_snprintf. *\briefthefunctionssnprintfproduceoutputaccordingtoaformat. *\paramstr:theoutputbuffer. *\paramsize:sizeallowwrittingtobuffer *\paramformat:formatstring *\paramap:variablelist *\returnsuccess:sizewrittentobuffer;failoroutputlongerthansize:-1 */ intwar_vsnprintf(char*str,size_tsize,constchar*format,va_listap) { intres; res=vsnprintf(str,size,format,ap); if(res>=size){ //tr_log(LOG_ERROR,"[v]snprintffailedoroutputlongerthanbuffer!"); printf("[v]snprintffailedoroutputlongerthanbuffer!\n"); return-1; }else returnres; } /*! *\fnwar_snprintf. *\briefthefunctionssnprintfproduceoutputaccordingtoaformat. *\paramstr:theoutputbuffer. *\paramsize:sizeallowwrittingtobuffer *\paramformat:formatstring *\returnsuccess:sizewrittentobuffer;fail:-1 */ intwar_snprintf(char*str,size_tsize,constchar*format,...) { intres; va_listap; va_start(ap,format); res=war_vsnprintf(str,size,format,ap); va_end(ap); returnres; } #defineCHECK_RC(rc,szInfo,szErrMsg,db)if(rc!=SQLITE_OK)\ {printf("%serror!\n",szInfo);\ printf("%s\n",szErrMsg);\ sqlite3_free(szErrMsg);\ sqlite3_close(db);\ return0;} intmain(intargc,char*argv[]) { sqlite3*db; char*dbPath="tr.db"; char*szErrMsg=0; intrc=0; rc=sqlite3_open(dbPath,&db); if(rc==SQLITE_OK){ printf("opensucceed\n"); } else{ printf("openfail\n"); } //char*szSql="SELECTtype,valueFROMtrWHEREid=3"; //char*szSql="insertintotrvalues(null,-1,'','false','false',0,'',1,0,'','node','')"; charszSql[128]; inti=1; //char*Sql="CREATETABLEtr(idINTEGERPRIMARYKEY,pidINTEGERDEFAULT-1,nameTEXTNOTNULLCOLLATENOCASE,rwvarchar(5)DEFAULT'true',getcvarchar(5)DEFAULT'false',nocINTEGERDEFAULT0,nocccharchar(3)DEFAULT'',ninINTEGERDEFAULT1,ilINTEGERDEFAULT0,aclvarchar(255)DEFAULT'',typevarchar(16)DEFAULT'node',valueTEXTDEFAULTNULL,UNIQUE(pid,name));"; //rc=sqlite3_exec(db,Sql,0,0,&szErrMsg); //CHECK_RC(rc,"createtable",szErrMsg,db); for(i=1;i<=30;i++) { /*begin*/ rc=sqlite3_exec(db,"BEGINEXCLUSIVE",NULL,NULL,&szErrMsg); CHECK_RC(rc,"begin",szErrMsg,db); war_snprintf(szSql,sizeof(szSql),"insertintotrvalues(null,%d,'jjhh','true','false',0,'',1,0,'','string','')",i); rc=sqlite3_exec(db,szSql,lib_get_value_callback,0,&szErrMsg); CHECK_RC(rc,"insertvalues",szErrMsg,db); if((rc==SQLITE_OK)&&((i%2)==0)) { rc=sqlite3_exec(db,"COMMIT",NULL,NULL,&szErrMsg); CHECK_RC(rc,"insertvalues",szErrMsg,db); war_snprintf(szSql,sizeof(szSql),"SELECTid,valueFROMtrWHEREpid=%dandname='%s'",i,"jjhh"); rc=sqlite3_exec(db,szSql,lib_get_value_callback,0,&szErrMsg); CHECK_RC(rc,"queryvalues",szErrMsg,db); } else { rc=sqlite3_exec(db,"ROLLBACK",NULL,NULL,&szErrMsg); CHECK_RC(rc,"insertvalues",szErrMsg,db); } sleep(5); } sqlite3_close(db); printf("happyeveryday!"); return0; }
希望本文所述对大家C语言程序设计有所帮助。