将dict.txt文件导入到数据库中
#include<myhead.h>
int main(int argc, const char *argv[])
{
//打开数据库
sqlite3 *db=NULL;
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 sql1[128]="create table if not exists dict (English char,Chinese char);";
char* errmsg=NULL;
if(sqlite3_exec(db,sql1,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr,"sqlite3_exec:%s __%d__\n",errmsg,__LINE__);
return -1;
}
printf("create table dict success\n");
//将dict.txt导入到数据库中
FILE *fp; //定义文件指针
//以只读的形式打开文件
if((fp=fopen("./dict.txt","r"))==NULL)
{
perror("fopen error");
return -1;
}
char buf[128]="";
char Eng[128]="";
char Cha[128]="";
int i=0,m=0,n=0;
int flag=0;
while(1)
{
bzero(buf,sizeof(buf));
bzero(Eng,sizeof(Eng));
bzero(Cha,sizeof(Cha));
if(fgets(buf,sizeof(buf),fp)==NULL)
{
break;
}
buf[strlen(buf)-1]='\0';
while(buf[i]!='\0')
{
if(buf[i]==' '&&flag==0)
{
m=i;
flag=1;
}
if(buf[i]!=' '&&buf[i-1]==' ')
{
n=i;
}
i++;
}
for(int j=0;j<m;j++)
{
Eng[j]=buf[j];
}
Eng[m]='\0';
char *p=buf+n;
strcpy(Cha,p);
//插入数据
char sql2[128]="";
sprintf(sql2,"insert into stu values(\"%s\",\"%s\");",Eng,Cha);
char *errmsg=NULL;
if(sqlite3_exec(db,sql2,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr,"sqlite3_exec:%s __%d__\n",errmsg,__LINE__);
return -1;
}
}
//关闭数据库
if(sqlite3_close(db)!=SQLITE_OK)
{
fprintf(stderr,"sqlite3_close:%s __%d__\n",errmsg,__LINE__);
return -1;
}
printf("close success\n");
return 0;
}