将dict.txt导入到数据库中(单词一列,意思一列)
#include <myhead.h>
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;
}
printf("sqlite3_open success\n");
//创建表格
char sql[128]="create table if not exists dict (word char ,mean chars);";
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("create table dict success\n");
//清空表格
char arr[128]="delete from dict;";
if(sqlite3_exec(db,arr,NULL,NULL,&errmsg) != SQLITE_OK)
{
fprintf(stderr,"sqlite3_exec:%s __%d__\n",errmsg,__LINE__);
return -1;
}
//打开文件
FILE *fp=NULL;
if((fp=fopen("./dict.txt","r"))==NULL)
{
perror("fopen error");
return -1;
}
int i=0;
int flag=0;
//插入数据
char buf[128]="";
char word[64]="";
char mean[64]="";
while(fgets(buf,sizeof(buf),fp) !=NULL)
{
int len=strlen(buf);
flag=0;
for(i=0;i<len;i++)
{
if(buf[i]!=' ')
{
word[i]=buf[i];
flag++;
}
else
{
break;
}
}
for(i=0;i<len;i++)
{
if(buf[flag+3+i]!='\n')
mean[i]=buf[flag+3+i];
}
sprintf(sql,"insert into dict values (\"%s\",\"%s\")",word,mean);
char* errmsg = NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
{
fprintf(stderr,"sqlite3_exec:%s __%d__\n",errmsg,__LINE__);
return -1;
}
bzero(buf,sizeof(buf));
bzero(word,sizeof(word));
bzero(mean,sizeof(mean));
}
printf("insert into stu success\n");
fclose(fp);
//关闭数据库
if(sqlite3_close(db) != SQLITE_OK)
{
fprintf(stderr,"sqlite3_open: %s %d __%d__\n",\
sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);
return -1;
}
printf("sqlite3_close success\n");
return 0;
}
运行结果
思维导图