网编day7

数据库词典插入

#include
int do_insert(sqlite3 *db,char* words,char* mean);
int main(int argc, const char *argv[])
{
	//打开数据库
	sqlite3 *db;
	if(sqlite3_open("./sq.db",&db)!=SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_open:%s %d __%d__\n",\
				sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);
		return -1;
	}
	printf("sqlite3_open success\n");

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

	char sql[128]="create table if not exists dict(words char,mean char);";
	char* errmsg=NULL;
	//创建一个表格
	if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_exec:%s __%d__\n",\
				errmsg,__LINE__);
		return -1;
	}
	printf("sqlite3_exec success\n");

	//读取文件内容
//	ssize_t res=0;
	char buf[128]="";
	char words[128];
	char mean[128];

	//定义变量i
	int static i=0;
	while(fgets(buf,sizeof(buf),fp)!=NULL)
	{
		//清空数组数据
		bzero(words, sizeof(words));
		bzero(mean, sizeof(mean));
			
		//将读取的内容分成name、meaning两部分存放
		for(i=0;' '!=buf[i];words[i]=buf[i],i++);
		for(;' '==buf[i];i++);
		for(int j=0;'\n'!=buf[i-1];mean[j]=buf[i],j++,i++);

		//调用插入函数
		do_insert(db,words,mean);
		bzero(buf, sizeof(buf));
	}
	printf("词典加载完成\n");
	//关闭文件描述符
	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;
	}
	printf("sqlite3_close success\n");
	return 0;
}

int do_insert(sqlite3 *db,char* words,char* mean)
{
	char buf[128]="";
	char* errmsg=NULL;
	sprintf(buf,"INSERT INTO dict VALUES('%s','%s');",words,mean);
	//插入函数
	if(sqlite3_exec(db,buf,NULL,NULL,&errmsg)!=SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_exec:%s __%d__\n",\
				errmsg,__LINE__);
		return -1;
	}
	return 0;
}

你可能感兴趣的:(jvm)