作业内容
- 将dict.txt的内容导入到数据库中
主要代码
#include <stdio.h>
#include <sqlite3.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//打开要读取的单词表
FILE* fp = fopen("./dict.txt","r");
//打开数据库
sqlite3* db = NULL;
if(sqlite3_open("./dict.db", &db) != SQLITE_OK)
{
printf("err_code:%d\n", sqlite3_errcode(db));
printf("errmsg:%s\n", sqlite3_errmsg(db));
fprintf(stderr, "__%d__ sqlite3_open failed\n", __LINE__);
return -1;
}
printf("sqlite3_open success\n");
//创建一个表格
char* sql1 = "create table if not exists dict (word char, meaning char);";
char* errmsg1 = NULL;
if(sqlite3_exec(db, sql1, NULL, NULL, &errmsg1) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg1);
return -1;
}
char buf[128];
char sql2[128] = "";
while(1)
{
if(fgets(buf, sizeof(buf), fp) == NULL)
{
break;
}
buf[strlen(buf)-1] = 0;
char* word = buf;
char* meaning = buf;
char* p = word;
while(*p++ != ' ');
p--;
char* q = p;
if(*(++p) == ' ')
{
*q = 0;
while(*p++ == ' ');
p--;
meaning = p;
}
else
{
p++;
while(*p++ != ' ');
q = p;
*q = 0;
while(*p++ == ' ');
p--;
meaning = p;
}
sprintf(sql2, "insert into dict values (\"%s\",\"%s\");", word, meaning);
char *errmsg2 = NULL;
if(sqlite3_exec(db, sql2, NULL, NULL, &errmsg2) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg2);
return -1;
}
}
//关闭数据库
if(sqlite3_close(db) != SQLITE_OK)
{
printf("err_code:%d\n", sqlite3_errcode(db));
printf("errmsg:%s\n", sqlite3_errmsg(db));
fprintf(stderr, "__%d__ sqlite3_open failed\n", __LINE__);
return -1;
}
return 0;
}
测试结果