ubuntu@ubuntu:~/internet/exercise/09_lib$ cat dict电子词典.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sqlite3.h>
int main(int argc, const char *argv[])
{
//创建并打开一个数据库
sqlite3* db;
if(sqlite3_open("./dict.db",&db)!=SQLITE_OK)
{
fprintf(stderr,"sqlite3_open:%d:%s__%d__",\
sqlite3_errcode(db),sqlite3_errmsg(db),__LINE__);
return -1;
}
printf("open database %s success\n\n","./dict.db");
//在数据库中创建一个表格用来存放单词
//在数据库中怎么写sql语句,在代码中就怎么写,最后分号可以省略
char sql[128] = "create table if not exists dict (word char,mean char);";
char* errmsg;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
{
fprintf(stderr,"sqlite3_exec:%s__%d__\n",errmsg,__LINE__);
return -1;
}
printf("create table dict success__%d__\n",__LINE__);
//插入单词
char text[128] = "";
char word[20]="";
char mean[50]="";
char buf[128]="";
//打开要读的文件
FILE* fd_r = fopen("./dict.txt","r");
while(1)
{
//如果读取到的是空格结束则放到第一列,如果是换行则放到第二列
int num = fscanf(fd_r,"%s",word);
if(num == EOF)
break;
fseek(fd_r,1,SEEK_CUR);
fgets(mean,sizeof(mean),fd_r);
sprintf(text,"insert into dict values (\"%s\",\"%s\");",word,mean);
if(sqlite3_exec(db,text,NULL,NULL,&errmsg) != SQLITE_OK)
{
fprintf(stderr,"sqlite3_exec:%s__%d__\n",errmsg,__LINE__);
return -1;
}
}
//关闭数据库,清空内存
sqlite3_close(db);
return 0;
}
将电子词典(四级词汇)导入到数据库
最新推荐文章于 2023-09-04 21:59:53 发布