sqlite3的事务功能实例

前端之家收集整理的这篇文章主要介绍了sqlite3的事务功能实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

代码功能

sql.txt中读出sql语句,并一一执行,若有一条执行失败,则所有执行全部不生效。回滚到执行前的状态。


#include <stdio.h>
#include <sqlite3.h>
#define sql_FILE "./sql.txt"
int commitsql(sqlite3 *db)
{
	int ret=0;         
	FILE *fp;          

	char buf[100]={0};
	char *errmsg = 0;
	char **azResult;
	int i,nRow=0,nColumn=0;
	fp = fopen(sql_FILE,"r");
	if(NULL == fp)     
		return -1;     
	ret = sqlite3_exec(db,"BEGIN EXCLUSIVE",NULL,&errmsg);    
	if(ret != sqlITE_OK)
	{
		printf("ret = %d,BEGIN EXCLUSIVE: %s",ret,errmsg);
	}
	while( NULL != fgets(buf,100,fp))
	{                       
		printf("%s\n",buf);
		if(0 == strncmp(buf,"select",6))
		{
			ret += sqlite3_get_table(db,buf,&azResult,&nRow,&nColumn,&errmsg);
			if(ret != sqlITE_OK)
			{
				printf("ret = %d,search table fail: %s\n",errmsg);
			}
			printf("row:%d column=%d\n",nRow,nColumn);
			for(i=nColumn;i<(nRow+1)*nColumn;i++)
			{
				printf("azResult[%d] = %s\n",i,azResult[i]);
			}
			sqlite3_free_table(azResult);
		}
		else
			ret += sqlite3_exec(db,&errmsg); 
		if(sqlITE_OK != ret)
		{
			printf("ret = %d,sql: %s\n",errmsg);
			break;
		}
	}      
	if(ret == sqlITE_OK)
	{
		ret=sqlite3_exec(db,"COMMIT",&errmsg);
		if(ret != sqlITE_OK)
		{
			printf("ret = %d,COMMIT: %s\n",errmsg);
		}
	}
	else
	{
		ret=sqlite3_exec(db,"ROLLBACK",ROLLBACK: %s\n",errmsg);
		}
		sqlite3_free(errmsg);
		fclose(fp); 
		return -2;
	}
	sqlite3_free(errmsg);
	fclose(fp); 

	return ret;
}

int main()
{
	sqlite3 *db;
	char *dbPath="test.db";  
	int ret = 0;        
	ret = sqlite3_open(dbPath,&db);  
	if(ret == sqlITE_OK)
	{  
		printf("open succeed\n");      
	}  
	else
	{              
		printf("open fail\n");         
	}  
	ret = commitsql(db);
	printf("ret = %d\n",ret);

	sqlite3_close(db);
}

猜你在找的Sqlite相关文章