将dict.txt导入到数据库中
单词一列,意思一列
#include <myhead.h>
int main(int argc, const char *argv[])
{
//打开数据库
sqlite3 *db;
if(sqlite3_open("./my.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 dic (word char,mean char);";
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 dic success\n");
//吧文档中的数据写入数据库中
//打开文件描述符
FILE *fd=NULL;
fd=fopen("./dict.txt","r");
if(NULL==fd)
{
printf("fopen error\n");
return -1;
}
char buf[128]="";
char word[30]="";
char mean[128]="";
int i=0;
int j=0;
while(1)
{
bzero(buf,sizeof(buf));
bzero(sql,sizeof(sql));
bzero(word,sizeof(word));
bzero(mean,sizeof(mean));
//循环读取数据一行一行读
if(NULL==fgets(buf,sizeof(buf),fd))
{
//读取完毕
printf("读取完毕\n");
break;
}
for(i=0;i<strlen(buf);i++)
{
// printf("1");
if(buf[i]==' ')
{
//printf("%d",i);
break;
}
}
buf[strlen(buf)-1] = 0;
//printf("i=%d",i);
for(j=0;j<i;j++)
{
word[j]=buf[j];
}
while(buf[i]==' ')
{
i++;
}
for(j=0,i;i<strlen(buf);i++,j++)
{
mean[j]=buf[i];
}
// strcpy(mean,&buf[i]);
//合成字符串
sprintf(sql,"insert into dic values (\"%s\",\"%s\");",word,mean);
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr,"sqlite3_exec:%s __%d__\n",errmsg,__LINE__);
return -1;
}
}
printf("write success\n");
//关闭文件描述符
fclose(fd);
//关闭数据库
if(sqlite3_close(db)!=SQLITE_OK)
{
fprintf(stderr,"sqlite3_close:%s %d __%d__\n",\
sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);
return -1;
}
printf("sqliet3_close success\n");
return 0;
}