作业需求:将单词表导入到表格中
实现过程:
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
#include <string.h>
int main(int argc, const char *argv[])
{
sqlite3 * db=NULL;
if(sqlite3_open("./word.db",&db)!=SQLITE_OK)
{
fprintf(stderr,"sqlite3_open fail:%d:%s\n",sqlite3_errcode(db),sqlite3_errmsg(db));
return -1;
}
printf("sqlite3_open success\n");
char sql[128]="create table if not exists word (english char,chinese char);";
char *errmsg=NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_exec:%s\n",__LINE__,errmsg);
return -1;
}
char filename[20];
printf("请输入要导入的文件名>>>");
scanf("%s",filename);
while(getchar()!=10);
FILE*fp=fopen(filename,"r");
char english[200],chinese[200];
int res=0;
while(1)
{
bzero(english,sizeof(english));
res=fscanf(fp,"%s",english); //读到空格结束
if(EOF==res)
{
break;
}
bzero(chinese,sizeof(chinese));
fgets(chinese,sizeof(chinese),fp); //读到换行结束
char sql[128]="";
sprintf(sql,"insert into word values (\"%s\",\"%s\")",english,chinese);
char *errmsg = NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_exec:%s\n",__LINE__,errmsg);
}
}
sqlite3_close(db);
fclose(fp);
return 0;
}
3.实验结果:
![](https://i-blog.csdnimg.cn/blog_migrate/b55f8ded6aab27f1d219b647aaa9c384.png)