导入单词表到sqlite3数据库
import.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
int main(int argc, const char *argv[])
{
sqlite3 *db = NULL;
// 如果数据库不存在,则创建后打开
// 如果存在则直接打开
if (sqlite3_open("./dict.db", &db) != SQLITE_OK)
{
fprintf(stderr, "sqlite3_open:%s errocode:%d\n",
sqlite3_errmsg(db), sqlite3_errcode(db));
return 0;
}
printf("打开数据库成功\n");
// 创建一个表
char sql[128] = "create table if not exists dict(eng char,ch char);";
char *errmsg = NULL;
if (sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "line:%d sqlite3_exec:%s errocode:%d\n",
__LINE__, sqlite3_errmsg(db), sqlite3_errcode(db));
return -1;
}
printf("创建表stu成功\n");
char ch[32] = "";
char line[64] = "";
FILE *fp = fopen("./dict.txt", "r");
if (NULL == fp)
{
perror("fopen");
return -1;
}
int res = 0;
int separator = 0;
while (1)
{
if (fgets(line, sizeof(line), fp) == NULL)
{
break;
};
line[strlen(line) - 1] = '\0';
for (int i = 0; line[i] != ' '; i++)
{
if (line[i + 1] == ' ' && line[i + 2] == ' ')
{
// 找到分隔符了
// 将i设置为分隔符
separator = i;
strcpy(ch, &line[i + 4]);
}
}
if (separator != 0)
{
line[separator] = 0;
}
printf("eng=%s\tchinese=%s\n", line, ch);
sprintf(sql, "insert into dict values (\"%s\",\"%s\");", line, ch);
if (sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "line:%d sqlite3_exec:%s errocode:%d\n",
__LINE__, sqlite3_errmsg(db), sqlite3_errcode(db));
return -1;
}
}
printf("insert success!\n");
return 0;
}