网络编程 day7

导入单词表到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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值