通过C实现sqlite3操作,导入电子词典

#include 
#include 
#include 
#include 
int main(int argc, const char *argv[])
{
	//创建并打开一个数据库
	sqlite3 *db = NULL;
	if(sqlite3_open("./dict.db",&db) != SQLITE_OK)
	{
		printf("sqlite3_open:%s %d __%d__\n",\
				sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);
		return -1;
	}
	printf("open database my.db success\n");

	//创建一个表格 create table stu (id int,name char,score float);
	//数据库中sql语句怎么写,这里就怎么写
	char sql[128] = "create table if not exists dict (word char,mean char);";
	char* errmsg = NULL;

	if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_open:%s %d __%d__\n",\
				errmsg,sqlite3_errcode(db),__LINE__);
		return -1;
	}
	printf("create table stu success\n");

	//打开文件
	FILE* fp = fopen("./dict.txt","r");
	if(NULL == fp)
	{
		perror("fopen");
		return -1;
	}

	//循环读取文件中的数据,一行一行的读取
	char buf[256] = "";
	char word[32] = "";
	char mean[200] = "";
	int count = 1;
	int i =0;
	char* ptr = NULL;

	while(1)
	{
		if(fgets(buf,sizeof(buf),fp) == NULL)
			break;
		buf[strlen(buf)-1] = 0;

		//分离单词和意思
		bzero(word,sizeof(word));
		bzero(mean,sizeof(mean));

		//获取" "子串在buf中的地址
		ptr = strstr(buf," ");
		if(NULL == ptr)
		{
			printf("没有找到对应子串\n");
			break;
		}
		strncpy(word,buf,ptr-buf);    //" "子串前面是单词
		strcpy(mean,ptr+3);           //" "子串后面是意思

		//插入到数据库中
		sprintf(sql,"insert into dict values(\"%s\",\"%s\");",word,mean);
		if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
		{
			printf("sqlite3_exec failed:%s __%d__\n",errmsg,__LINE__);
			return -1;
		}
	}

	//关闭文件
	fclose(fp);
	//关闭数据库
	if(sqlite3_close(db) != SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_close:%s %d __%d__\n",\
				sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);
		return -1;
	}
	return 0;
}

通过C实现sqlite3操作,导入电子词典_第1张图片

你可能感兴趣的:(c语言,sqlite,c#)