将dict.txt导入到数据库中:
#include<myhead.h>
int main(int argc, const char *argv[])
{
//打开数据库
sqlite3 *db = NULL;
if(sqlite3_open("./dict.db",&db)!=SQLITE_OK)
{
printf("sqlite3_open faile:%s __%d__\n",sqlite3_errmsg(db),__LINE__);
return -1;
}
printf("创建表格 dict.db 成功__%d__\n",__LINE__);
//创建表格
char sql[128]="create table if not exists dict (word char, mean char);";
char *errmsg=NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("sqlite3_exec failed:%s_%d_\n",errmsg,__LINE__);
return -1;
}
printf("create table dict success __%d__\n",__LINE__);
//打开文件
FILE* fp=fopen("./dict.txt","r");
if(NULL==fp)
{
perror("fopen");
return -1;
}
//循环读取文件中的数据,一行一行读
char buf[256]="";
char word[32]="";
char mean[200]="";
int count = 1;
int i=0;
while(1)
{
if(fgets(buf,sizeof(buf),fp)==NULL)
break;
buf[strlen(buf)-1]=0;
//分离单词和意思
bzero(word,sizeof(word));
bzero(mean,sizeof(mean));
for(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(mean,buf+i+2);
break;
}
}
//插入到数据库中
sprintf(sql,"insert into dict values(\"%s\",\"%s\");",word,mean);
printf("sql=%s\n",sql);
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("sqlite3_exec failed:%s__%d__\n",errmsg,__LINE__);
return -1;
}
}
//关闭文件
fclose(fp);
//关闭数据库
if(sqlite3_close(db)!=SQLITE_OK)
{
printf("sqlite3_close failed:%s__%d__\n",sqlite3_errmsg(db),__LINE__);
return -1;
}
printf("slqite3 sq.db close success\n");
return 0;
}