day 0904

#include 
#include 
int do_create(sqlite3 *db);
int do_init(sqlite3 *db);
int msg_get(FILE *fp, char* pEng, char *pChin);
int do_insert(sqlite3 *db, char *English, char *Chinese);
int main(int argc, const char *argv[])
{
	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;
	}

	do_init(db);

	FILE *fp;
	char English[32] = "";
	char Chinese[64] = "";
	if(NULL == (fp = fopen("./dict.txt", "r")))
	{
		printf("%d",__LINE__);
		perror("fopen error");
		return -1;
	}

	do_create(db);

	while(1)
	{
		bzero(English, sizeof(English));
		bzero(Chinese, sizeof(Chinese));
		msg_get(fp, English, Chinese);

		do_insert(db, English, Chinese);
		printf("%s\t%s\n",English, Chinese);

		if(feof(fp))
		{
			printf("导入成功\n");
			break;
		}
	}
	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;
}



int do_create(sqlite3 *db)
{
	if(NULL==db)
	{
		printf("创建失败\n");
		return -1;
	}
	char sql[128] = "create table if not exists dict(Endlish char, Translation 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;
	}
		
}
int do_init(sqlite3 *db)
{
	if(NULL==db)
	{
		printf("创建失败\n");
		return -1;
	}
	char sql[128] = "drop table dict.db";
	char *errmsg = NULL;
	if(sqlite3_exec(db, sql,NULL, NULL,&errmsg)!=SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_exec:%d  %s\n",__LINE__, sqlite3_errmsg(db));
		return -1;
	}
	return 0;
}

int msg_get(FILE *fp, char* pEng, char *pChin)
{
	char temp = 0;
	int i =0;
	while((temp = fgetc(fp))!=' ')
	{
		pEng[1] = temp;
		i++;
		if(feof(fp))
		{
			return 0;
		}
	}
	i = 0;
	while(fgetc(fp)==' ');
	fseek(fp,-1,SEEK_CUR);
	while((temp = fgetc(fp))!='\n')
	{
		pChin[1] = temp;
		i++;
		if(feof(fp))
		{
			pChin[i-1] = 0;
			break;
		}
	}
	return 0;
}

int do_insert(sqlite3 *db, char *English, char *Chinese)
{
	if(NULL==db)
	{
		printf("创建失败\n");
		return -1;
	}
	char sql[128] = "";
	snprintf(sql, sizeof(sql), "insert into dict values(\"%s\", \"%s\")",English, Chinese);
	
	char *errmsg = NULL;
	if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
	{
		fprintf(stderr, "sqlite3_exec: %s %d __%d__\n",\
				sqlite3_errmsg(db), sqlite3_errcode(db), __LINE__);
		return -1;
	}
	return 0;
}

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