1、将.txt表数据导入数据库中
#include <myhead.h>#define ERR_MSG(msg) do{\fprintf(stderr,"__%d__:",__LINE__);\perror(msg);\
}while(0)int main(int argc, const char *argv[])
{//以只读的方式打开dict.txt文件FILE* fd;if((fd=fopen("./dict.txt","r")) == NULL){ERR_MSG("open");return -1;}//打开数据库sqlite3* db=NULL;if(sqlite3_open("./dict.db", &db) != 0){fprintf(stderr,"__%d__sqlite3_open: %s",\__LINE__, sqlite3_errmsg(db));return -1;}//创建数据表char sql[128] = "create table if not exists dict(word char,mean char);";char *errmsg = NULL;if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != 0){fprintf(stderr, "__%d__create:%s\n",\__LINE__,errmsg);return -1;}printf("create success\n");char buf[128]="";char word[50]="";char mean[50]="";while(fgets(buf,128,fd) != NULL){buf[strlen(buf)-1]=0;for(int i=0;i<strlen(buf);i++){if(buf[i]!=' ' && buf[i+1]==' ' && buf[i+2]==' '){strcpy(word,buf,i+1);}if(buf[i]==' ' && buf[i+1]==' ' && buf[i+2]!=' '){strcpy(mean,buf+i+2);}}//将word,mean插入到数据库中char sql[128]="";sprintf(sql,"insert into dict values(\"%s\",\"%s\");", word, mean);char *errmsg = NULL;if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) !=0){fprintf(stderr, "__%d__insert:%s\n",\__LINE__,errmsg);return -1;}//清空buf,word,meanbzero(buf,128);bzero(word,50);bzero(mean,50);}printf("导入成功\n");//关闭文件fclose(fd);//关闭数据库sqlite3_close(db);return 0;
}
2、思维导图