【网络编程】Day7 sqlite3

将dict.txt导入到数据库中:单词一列,意思一列

代码dict_sql.c:

#include <myhead.h>

int insert(sqlite3 *db);
int main(int argc, const char *argv[])
{

	//1. 创建或直接打开一个数据库: dict.db
	sqlite3* db = NULL;
	if(sqlite3_open("./dict.db",&db) != SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_open failed:%s,%d, __%d__\n",sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);
		return -1;
	}
	printf("数据库打开成功\n");

	//2.创建一张表格
	char sql[128] = "create table if not exists dict(word char,mean char)";  //数据库中sql语句一样的写法,可修改
	char *errmsg=NULL;   //错误信息
	if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_exec:%s, __%d__\n",errmsg,__LINE__);
		return -1;
	}
	printf("创建表格 dict 成功\n");

	//3.插入数据到数据库中
	insert(db); 
	 
	//4.关闭数据库
	if(sqlite3_close(db) != SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_close failed:%s,%d, __%d__\n",sqlite3_errmsg(db),sqlite3_errcode(db),__LINE__);
		return -1;
	}
	printf("成功关闭数据库\n");
	return 0;
}


int insert(sqlite3 *db)
{
	FILE *fp;
	char word[100];
	char mean[100];
	char buf[300]="";

	char st[300] ="";  
	char *errmsg = NULL; 

	//打开要插入的文件
	if(NULL == (fp=fopen("./dict.txt","r")))
	{
		perror("fopen error");
		return -1;
	}

	//读取每行
	while((fgets(buf,sizeof(buf),fp)) != NULL)
	{
		int i=0;
		char *p = buf;
		memset(word,0,sizeof(word));
		buf[strlen(buf)-1] = '\0';
		while(*p!=' ')  //32
		{
			word[i]=*p;
			p++;
			i++;	
		}

		p++;
        if(*p !=' ')
        {
            word[i] = ' ';
            i++;
		    while(*p!=' ')  //32
		    {
			    word[i]=*p;
			    p++;
			    i++;	
		    }
            word[i]='\0'; 
        }
       	else word[i]='\0'; 

        p++;
        while(*p==' ' && *p != '\0')
        {
            p++;
        } 


//处理'问题 ?
		char *q = p;
		while(*q != '\0')
		{
			if(*q == '\'')
			{
				*q = '.';
			}  
			q++;
		}
		q = word;
		while(*q != '\0')
		{
			if(*q == '\'')
			{
				*q = '.';
			}
			q++;
		}

		strcpy(mean, p);
		sprintf(st,"insert into dict values('%s','%s')",word,mean);
		if(sqlite3_exec(db,st,NULL,NULL,&errmsg) != SQLITE_OK)
		{
			fprintf(stderr,"插入失败,%s,在第%d行\n",errmsg,__LINE__);
			return -1;
		}	
 		memset(buf,0,sizeof(buf));
	}
	fclose(fp);
	printf("单词插入成功\n");
	return 0;
}

运行如下:

ubuntu@ubuntu:day7_sqlite3$ gcc 02_dict_sql.c  -lsqlite3
ubuntu@ubuntu:day7_sqlite3$ ./a.out 
数据库打开成功
创建表格 dict 成功
单词插入成功
成功关闭数据库

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值