day40:网编day7,数据库指令应用(将dict.txt导入数据库中)

将dict.txt导入到数据库中:

#include 

int do_insert(sqlite3* db,FILE *fp)
{
	int count=0;
	char buf[64]="";
	char sql[128]="";
	char *p;
	char *errmsg=NULL;

	while(1)
	{
		if(count++ ==7987)
			break;
		bzero(buf,sizeof(buf));
		bzero(sql,sizeof(sql));
		p=buf;
		fgets(buf,sizeof(buf),fp);
		buf[strlen(buf)-1]=0;
		while(*p!=32)
		{
			p++;
		}
		*p=0;
		p++;
		while(*p==32)
		{
			p++;
		}
		sprintf(sql,"INSERT INTO dict VALUES(\"%s\",\"%s\");",buf,p);

		if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
		{
			fprintf(stderr,"sqlite3_exec:%s %d __%d__\n",\
					errmsg,sqlite3_errcode(db),__LINE__);
			return -1;
		}
	}
	printf("insert success\n");
}
int main(int argc, const char *argv[])
{
	FILE *fp;;
	if((fp = fopen("./dict.txt","r")) == NULL)
	{
		perror("fopen");
		return -1;
	}
	printf("fopen success\n");

	sqlite3 *db;
	if(sqlite3_open("./dict.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");

	char buf[128]="create table if not exists dict(word char,translate char)";
	char *errmsg=NULL;
	if(sqlite3_exec(db,buf,NULL,NULL,&errmsg)!=SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_open:%s %d __%d__\n",\
				errmsg,sqlite3_errcode(db),__LINE__);
		return -1;
	}

	do_insert(db,fp);

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

你可能感兴趣的:(数据库)