作业:将dict.txt文档导入到数据库中
要求:英文一列,解释一列
#include <stdio.h>
#include <sqlite3.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
//创建并打开数据库
sqlite3 *db;
if(sqlite3_open("./dict.db", &db) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_open: %d|%s\n",\
__LINE__, sqlite3_errcode(db), sqlite3_errmsg(db));
return -1;
}
printf("sqlite3_open success __%d__\n", __LINE__);
//创建表格
char sel[128] = "create table if not exists dict (word char, msg char);";
char *errmsg = NULL;
if(sqlite3_exec(db, sel, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec: %d|%s\n",\
__LINE__, sqlite3_errcode(db), sqlite3_errmsg(db));
return -1;
}
printf("sqlite3_exec success __%d__\n", __LINE__);
//拷贝文件
FILE *fd = fopen("./dict.txt", "r");
if(fd < 0)
{
perror("fopen");
return -1;
}
char buf[128] = "";
char *ret = NULL;
char word[50] = "";
char *means = NULL;
char insert[128] = "";
int size = 0;
while(1)
{
int i=0;
//获取一行数据
ret = fgets(buf, sizeof(buf), fd);
if(ret < 0)
{
perror("fgets");
return -1;
}
//如果读取完毕则退出
if(NULL == ret)
{
printf("读取完毕退出\n");
break;
}
means = ret;
while(*ret != ' ')
{
word[i++] = *ret++;
}
while(*means != ' ')
{
means++;
}
sprintf(insert, "insert into dict values (\"%s\", \"%s\")", word, means);
if(sqlite3_exec(db, insert, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec: %d|%s\n",\
__LINE__, sqlite3_errcode(db), sqlite3_errmsg(db));
return -1;
}
}
//关闭数据
if(sqlite3_close(db) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_open: %d|%s\n",\
__LINE__, sqlite3_errcode(db), sqlite3_errmsg(db));
return -1;
}
printf("sqlite3_open success __%d__\n", __LINE__);
fclose(fd);
return 0;
}
结果: