目录
将dict.txt导入到数据库中单词一列,意思一列
代码
结果
思维导图
将dict.txt导入到数据库中单词一列,意思一列
代码
#include<myhead.h>
#include<sqlite3.h>
int do_create(sqlite3 *db);
int do_insert(sqlite3 *db, char * English, char *Chinese);
int msg_get(FILE *fp, char*pEng, char *pChin);
int do_init(sqlite3 *db);
int main(int argc, const char *argv[])
{
//打开数据库
sqlite3 * db;
if(sqlite3_open("./dict.db", &db) != SQLITE_OK){
printf("%d:sqlite3_open error %s\n",__LINE__, sqlite3_errmsg(db));
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){
//从dict.txt中读取一行的数据
bzero(English, sizeof(English));
bzero(Chinese, sizeof(Chinese));
msg_get(fp, English, Chinese);
//将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){
printf("%d:sqlite3_close error %s\n",__LINE__, sqlite3_errmsg(db));
return -1;
}
//关闭文件
fclose(fp);
return 0;
}
int msg_get(FILE *fp, char* pEng, char *pChin){
char tmp = 0;
int i = 0;
while((tmp = fgetc(fp))!=' '){
pEng[i] = tmp;
i++;
if(feof(fp)){
return 0;
}
}
i = 0;
while(fgetc(fp)==' ');
fseek(fp,-1,SEEK_CUR);
while((tmp = fgetc(fp))!='\n'){
pChin[i] = tmp;
i++;
if(feof(fp)){
pChin[i-1] = 0;
break;
}
}
return 0;
}
int do_create(sqlite3 *db){
if(db == NULL){
printf("数据表不存在\n");
return -1;
}
char sql[128] = "create table if not exists dict(ENGLISH char, TRANSLATION char);";
char *errmsg = NULL;
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK){
printf("%d:sqlite3_exec error %s\n",__LINE__, sqlite3_errmsg(db));
return -1;
}
//创建成功
return 0;
}
int do_init(sqlite3 *db){
if(db == NULL){
printf("数据表不存在\n");
return -1;
}
char sql[128] = "drop table dict;";
char *errmsg = NULL;
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK){
printf("%d:sqlite3_exec error %s\n",__LINE__, sqlite3_errmsg(db));
return -1;
}
//创建成功
return 0;
}
//插入表格函数
int do_insert(sqlite3 *db, char * English, char *Chinese){
if(db == NULL){
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){
printf("%d:sqlite3_exec error %s\n",__LINE__, sqlite3_errmsg(db));
return -1;
}
return 0;
}