将文本批量写入数据库
#include<myhead.h>
int main(int argc, const char *argv[])
{
char word[128];
char mean[128];
sqlite3 *db;
if(sqlite3_open("./sq.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 dict (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 stu success\n");
FILE *fp;
if((fp=fopen("dict.txt","r"))==NULL){
perror("fopen error");
return 0;
}
char temp[128];
while(1){
int ret = fscanf(fp,"%s %s",word,mean);
if(ret ==-1){
break;
}
while(1){
fscanf(fp,"%s",temp);
if((temp[1]=='.'&&temp[2]<150)||temp[2]=='.'||temp[3]=='.'){
strcat(mean,temp);
}
else{
fseek(fp,-strlen(temp),SEEK_CUR);
break;
}
}
bzero(temp,sizeof(temp));
int i,k;
i=k=0;
for( i;i<strlen(word);i++){
temp[k]=word[i];
if(word[i]=='\''){
k++;
temp[k]=word[i];
}
k++;
}
printf("%s %s\n",temp,mean);
sprintf(sql,"insert into dict values('%s','%s');",temp,mean);
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK){
fprintf(stderr,"sqlite3_exec:%s __%d__\n",errmsg,__LINE__);
return -1;
}
bzero(sql,sizeof(sql));
bzero(word,sizeof(word));
bzero(mean,sizeof(mean));
}
if(sqlite3_close(db)!=SQLITE_OK){
fprintf(stderr,"sqlite3_close:%s %d __%d__",\
sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);
return -1;
}
printf("sqlite3_close success\n");
return 0;
}