Day8(网络编程)

该代码示例展示了如何用C++程序打开sqlite3数据库,创建表格,然后从dict.txt文件中读取数据并插入到数据库的word和msg两列。程序处理文件读取和数据库操作,当遇到错误时提供错误信息。
摘要由CSDN通过智能技术生成
作业:将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;
}

结果:

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值