将单词文件导入数据库中:
#include <myhead.h>
int main(int argc, const char *argv[])
{
//创建数据库
sqlite3 *db = NULL;
if(sqlite3_open("./my.db",&db) != SQLITE_OK){
fprintf(stderr,"__%d__ sqlite3_open : %d | %s\n",__LINE__,sqlite3_errcode(db),sqlite3_errmsg(db));
return -1;
}
printf("open success\n");
//打开文件
FILE *fp = fopen("dict.txt","r");
if(NULL == fp){
ERR_MSG("fopen");
return -1;
}
//创建表格
char sql[128] = "create table if not exists dictionary (word char, mean char);";
char *errmsg = NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK){
fprintf(stderr,"__%d__sqlite3_exec : %s\n",__LINE__,errmsg);
return -1;
}
printf("create table success\n");
//读取文件中字符串
char buf[128] = "";
char buf_word[128] = "";
char buf_mean[128] = "";
char *p = NULL;
while(1){
bzero(buf,sizeof(buf));
bzero(buf_word,sizeof(buf_word));
bzero(buf_mean,sizeof(buf_mean));
if(fgets(buf,sizeof(buf),fp) == NULL){
break;
}
p = buf;
int i=0;
int j=0;
while(1){
if(*p == ' '&& *(p+1) == ' '){
while(1){
p++;
//当指向不是空格时就是单词意思
if(*p != ' ')
break;
}
break;
}
//一个一个读取没到空格之前的数据,即单词word
buf_word[i] = *p;
i++;
p++;
}
strcpy(buf_mean,p);
buf_mean[strlen(buf_mean)-1] = 0;
char buff[128] = "";
sprintf(buff,"insert into dictionary values ('%s', '%s');",buf_word,buf_mean);
char *errmsg = NULL;
sqlite3_exec(db,buff,NULL,NULL,&errmsg);
}
//关闭数据库
if(sqlite3_close(db) != SQLITE_OK){
fprintf(stderr, "__%d__ sqlite3_close: %d | %s\n", __LINE__, sqlite3_errcode(db), sqlite3_errmsg(db));
return -1;
}
printf("close success\n");
fclose(fp);
return 0;
}
实现: