将dict.txt导入到数据库中
要求:单词一列,意思一列
#include <stdio.h>
#include <sqlite3.h>
#include <string.h>
int main(int argc, char const *argv[])
{
//打开数据库
sqlite3 *db = NULL;
int erro = 0, errc = 0;
if((erro = sqlite3_open("./dict.db", &db))!= 0)
{
printf("%d:%d, %s\n", __LINE__, erro, sqlite3_errmsg(db));
return -1;
}
printf("打开成功\n");
//创建表格
char *ptr = "create table if not exists stu (word char, idea char); ";
char *errmsg = NULL;
if(sqlite3_exec(db, ptr, NULL, NULL, &errmsg) != 0)
{
printf("%d:%s\n", __LINE__, errmsg);
return -1;
}
printf("表格创建成功\n");
FILE * fp = fopen("./dict.txt", "r");
if(fp== NULL)
{
perror("fopen");
return -1;
}
printf("文件打开成功\n");
char word[64] = "", idea[64] = "", str[128] = "";
char *errmsg1 = NULL;
int res = 0;
while(1)
{
res = fscanf(fp, "%s ",word);
if(EOF == res)
break;
fgets(idea,sizeof(idea), fp);
idea[strlen(idea)-1] = '\0';
sprintf(str, "insert into stu values (\"%s\", \"%s\");", word, idea);
if(sqlite3_exec(db, str, NULL, NULL, &errmsg1) != 0)
{
printf("%d:%s\n", __LINE__, errmsg1);
return -1;
}
}
if(fclose(fp) < 0)
{
perror("fclose");
return -1;
}
printf("文件关闭成功\n");
if((erro = sqlite3_close(db))!= 0)
{
printf("%d:%d, %s\n", __LINE__, erro, sqlite3_errmsg(db));
return -1;
}
printf("关闭成功\n");
return 0;
}