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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sqlite3.h>
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值