代码:
#include<stdio.h>
#include<sqlite3.h>
#include<stdlib.h>
#include<string.h>
//将单词导入到数据库
int sqlite3_word(sqlite3* db)
{
char sql[128]="";
char *errmsg=NULL;
//打开单词文件
FILE *fd =fopen("./dict.txt","r");
if(NULL==fd)
{
perror("fopen");
return -1;
}
printf("词典导入中请稍后..\n");
char buf[512]="",word[128]="",explain[128]="";
//循环读取文件的每一行内容
while(1)
{
bzero(word,sizeof(word));
bzero(explain,sizeof(explain));
if(fgets(buf,sizeof(buf),fd)==NULL)
{
printf("词典导入完毕\n");
return -1;
}
buf[strlen(buf)-1]=0;
//将单词和解释分开
for(int i=0;i<strlen(buf)-2;i++)
{
if(buf[i]!=' '&&buf[i+1]==' '&&buf[i+2]==' ')
{
strncpy(word,buf,i+1);
}
else if(buf[i]==' '&&buf[i+1]==' '&&buf[i+2]==' ')
{
strcpy(explain,(buf+i+2));
break;
}
}
//插入数据库
sprintf(sql,"insert into worddata values(\"%s\",\"%s\");",word,explain);
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr,"__%d__sqlite3_exec:%s\n",__LINE__,errmsg);
return -1;
}
}
fclose(fd);
}
int main(int argc,const char *argv[])
{
//如果数据库不存在,则创建后打开
//如果存在则直接打开
sqlite3* db=NULL;
if(sqlite3_open("./word.db",&db)!=SQLITE_OK)
{
fprintf(stderr,"sqlite3_open: %s errorde:%d\n",sqlite3_errmsg(db),sqlite3_errcode(db));
return -1;
}
printf("sqlite3_open success\n");
//创建一个表
//注意:C代码中编写的sql语句与在数据库中编写的一致
char sql[128]="create table if not exists worddata (word char,explain char);";
char* errmsg =NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_exec:%s\n",__LINE__,errmsg);
return -1;
}
printf("create table worddata success\n");
//将单词导入数据库
sqlite3_word(db);
//关闭数据库
if(sqlite3_close(db)!=SQLITE_OK)
{
fprintf(stderr,"sqlite3_open: %s errorde:%d\n",sqlite3_errmsg(db),sqlite3_errcode(db));
return -1;
}
return 0;
}
运行结果: