#include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//打开数据库
sqlite3* db =NULL;
if(sqlite3_open("./dict.db",&db) != SQLITE_OK)
{
fprintf(stderr,"__%d__ sqlite3 open failed:%s\n"\
,__LINE__,sqlite3_errmsg(db));
return -1;
}
printf("sqlite3_open success\n");
//创建一个表格
char sql[128] = "create table if not exists dictary (word char, mean char);";
char* errmsg = NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) !=SQLITE_OK)
{
fprintf(stderr,"__%d__ sqlite3 exec failed:%s\n"\
,__LINE__,errmsg);
return -1;
}
printf("create table success\n");
//把电子词典的内容倒到数据库中
FILE *fd=fopen("./dict.txt","r");
if(NULL==fd)
{
perror("fopen");
return -1;
}
char buf[128]="";
char word[64]="",mean[64]="";
while(1)
{
bzero(word,sizeof(word));
bzero(mean,sizeof(mean));
//fgets读完一行会停止读取
char* res=fgets(buf,sizeof(buf),fd);
if(NULL==res) break;
buf[strlen(buf)-1]=0; //去掉自动补上的\0
//分离单词和意思
for(int i=0;i<strlen(buf)-2;i++)
{
if(buf[i]!=' '&&buf[i+1]==' '&&buf[i+2]==' ')
{
strncpy(word,buf,i+1);
// printf("%s\n",word);
}
else if(buf[i]==' '&&buf[i+1]==' '&&buf[i+2]!=' ')
{
strcpy(mean,(buf+i+2));
// printf("%s\n",mean);
break;
}
}
//插入到数据库中
sprintf(sql,"insert into dictary values(\"%s\",\"%s\");",word,mean);
if(sqlite3_exec(db ,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr,"__%d__ sqlite3 exec failed:%s\n"\
,__LINE__,errmsg);
return -1;
}
}
//关闭数据库
if(sqlite3_close(db) != SQLITE_OK)
{
fprintf(stderr,"__%d__ sqlite3 close failed:%s\n"\
,__LINE__,sqlite3_errmsg(db));
}
printf("sqlite3_close success\n");
//关闭文件描述符
fclose(fd);
return 0;
}
将.txt电子词典导入sqlite3数据库
最新推荐文章于 2024-08-18 10:54:05 发布