【Linux】特别篇--sqlite3数据库的使用



一、数据库基本概念(了解)

数据库基本概念

  • 数据(Data)
    能够输入计算机并能被计算机程序识别和处理的信息集合。
  • 数据库 (Database)
    数据库是在数据库管理系统管理和控制之下,存放在存储介质上的数据集合

常用的数据库

  • 大型数据库
    Oracle公司是最早开发关系数据库的厂商之一,其产品支持最广泛的操作系统平台。目前Oracle关系数据库产品的市场占有率名列前茅。
    IBM 的DB2是第一个具备网上功能的多媒体关系数据库管理系统,支持包Linux在内的一系列平台。
  • 中型数据库
    Server是微软开发的数据库产品,主要支持windows平台。
  • 小型数据库
    mySQL是一个小型关系型数据库管理系统,开发者为瑞典MySQL AB公司,2008年被Sun公司收购,开放源码

二、基于嵌入式的数据库(了解)

  • 基于嵌入式Linux的数据库主要有SQLite, Firebird, Berkeley DB, eXtremeDB
  • Firebird是关系型数据库,功能强大,支持存储过程、SQL兼容等
    SQLite关系型数据库,体积小,支持ACID事务
  • Berkeley DB中并没有数据库服务器的概念,它的程序库直接链接到应用程序中
  • eXtremeDB是内存数据库,运行效率高

三、SQLite 基础(了解)

  • SQLite的源代码是C,其源代码完全开放。SQLite第一个Alpha版本诞生于2000年5月。 他是一个轻量级的嵌入式数据库。
  • SQLite有以下特性:
    • 零配置一无需安装和管理配置;
    • 储存在单一磁盘文件中的一个完整的数据库;
    • 数据库文件可以在不同字节顺序的机器间自由共享;
    • 支持数据库大小至2TB
    • 足够小,全部源码大致3万行c代码,250KB
    • 比目前流行的大多数数据库对数据的操作要快;
  • 缺点:
    无法判断数据进入数据库的类型是否正确

四、创建数据库

1、sqlite3数据库的安装

ubuntu在线安装:

  • 软件安装:sudo apt-get install sqlite3
  • 库的安装:sudo apt-get install libsqlite3-dev

注:下载前ubuntu一定要联网

2、sqlite3数据库的使用

  • 1、手工创建:用户在Linux的命令行界面中输入

例如:
sqlite3 文件名.db
SQLite version 3.7.2
Enter “.help” for instructions
Enter SQL statements terminated with a “;”
sqlite>

  • 2、代码创建
    在代码中调用动态库,创建数据库

五、数据库常用命令介绍

1、系统命令 , 都以'.'开头
	 .help   帮助手册
     .exit    退出
     .quit    退出
     .table   查看有哪些表
     .schema  查看表的结构
      
2、sql语句, 都以‘;’结尾

    (1) 创建一张表
        例如:create table stuinfo(id integer, name text, age integer, score float);
    
    (2) 插入一条记录
        insert into stuinfo values(1001, 'zhangsan', 18, 80);
        部分数据:insert into stuinfo (id, name, score) values(1002, 'lisi', 90);

    3-- 查看数据库记录
        select * from stuinfo;  查询全部
        select * from stuinfo where score = 80;  条件查询
        select * from stuinfo where score = 80 and name= 'zhangsan';
        select * from stuinfo where score = 80 or name='wangwu';
        select name,score from stuinfo;  查询指定的字段
        select * from stuinfo where score >= 85 and score < 90;

    4-- 删除一条记录
        delete from stuinfo where id=1003 and name='zhangsan';

    5-- 更新一条记录
        update stuinfo set age=20 where id=1003;
        update stuinfo set age=30, score = 82 where id=1003;

    6-- 删除一张表
        drop table stuinfo;

    7-- 增加一列
        alter table stuinfo add column sex char;

    8-- 删除一列
        create table stu as select id, name, score from stuinfo;
        drop table stuinfo;
        alter table stu rename to stuinfo;

 数据库设置自增键:
 create table info(id integer primary key autoincrement, name vchar);

六、SQLite编程接口

int sqlite3_open
(
	const char *filename,   /* Database filename (UTF-8) */
	sqlite3 **ppDb          /* OUT: SQLite db handle */
);

返回值:成功0 SQLITE_OK , 出错返回错误码

  • 功能:打开数据库
  • 参数
    • filename 数据库名称
    • ppdb 数据库句柄

int sqlite3_close(sqlite3* db);

返回值:成功0 SQLITE_OK , 出错返回错误码

  • 功能关闭数据库
  • 参数:db - 数据库句柄

const char *sqlite3_errmsg(sqlite3*db);
  • 功能:得到错误信息的描述
  • 参数: db - 数据库句柄

int sqlite3_exec(
   sqlite3* db,                                  /* An open database */
  const char *sql,                           /* SQL to be evaluated */
  int (*callback)(void* arg,int,char**,char**),  /* Callback function */
  void * arg,                                    /* 1st argument to callback */
  char **errmsg                              /* Error msg written here */
  );

返回值:成功返回SQLITE_OK

  • 功能:执行一条sql语句
  • 参数:
    • db : 数据库句柄
    • sql : sqlite语句
    • callback : 回调函数,只有在查询时,才传参
    • arg : 为回调函数传递参数
    • errmsg : 错误消息

查询回调函数:

int (*callback)(void* arg,int ncolumns ,char** f_value,char** f_name),  /* Callback function */
  • 功能:查询语句执行之后,会回调此函数
  • 参数
    • arg : 接收sqlite3_exec 传递来的参数
    • ncolumns : 列数
    • f_value : 列的值得地址
    • f_name : 列的名称
      返回值:0

不使用回调函数得到

int sqlite3_get_table
(
  sqlite3 *db,          /* An open database */
  const char *zSql,     /* SQL to be evaluated */
  char ***pazResult,    /* Results of the query */
  int *pnRow,           /* Number of result rows written here */
  int *pnColumn,        /* Number of result columns written here */
  char **pzErrmsg       /* Error msg written here */
);

返回值:成功返回0失败返回错误码

  • 功能:执行SQL操作
    • db:数据库句柄
    • sql:sqlite语句
    • resultp:用来指向sql执行结果的指针
    • nrow:满足条件的记录的数目
    • ncolumn:每条记录包含的字段数目
    • errmsg:错误信息指针的地址

示例:
编译记得加:-lsqlite3

假如我家开了个水果超市,有以下水果,想实现自动化管理,扫描二维码就能知道当前的水果状态,进货几天了,
好久需要再次进货,那些水果畅销,那些水果不畅销,那些水果春夏秋冬的价格波动,好,那么现在我想将
这些信息保存在数据库中,那么我应该怎么做;
提示: 建立一张fruit表,
假如水果有: 苹果,香蕉,梨,橘子,葡萄....(可以自己查一下英文保存到数据库)
水果价格: 苹果 5元/斤 香蕉 3元/斤 梨 3.5元/斤 橘子2.5元/斤 葡萄 8元/斤....
当前存货: 苹果 80斤 香蕉 200斤 梨 50斤 橘子300斤 葡萄 100斤....
超市每天水果都有进货和卖出嘛,水果的价格随着季节和天气也会有波动,顾客也会看一下每天水果的价格的嘛,
所以要求,根据上述提示,利用数据库完成水果店各种水果的增(进货)删(卖出)改(波动)查(看价格)功能。
并将进出货的时间
/*************************************************************************
  > File Name: fruit_sqlite.c
  > Author: xiuchengzhen
  > CSDN: xiuchengzhen.blog.csdn.net
  > Created Time: Tue 05 Apr 2022 04:58:41 AM PDT
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<sqlite3.h>
#include<unistd.h>
#include<time.h>
#include<string.h>

#define FRUIT "fruit.db"
#define TIME "time.db"

sqlite3 *fruit; //水果表
static int key = 1; //表头开关

void Add_fruit()
{
	int user = 0;
	char kind[20] = {0}, *errmsg, order[128] = {0}, ti[13] = {0};
	int price, surplus;
	time_t now;
	struct tm *tim;

	printf("========================\n");
	printf("1 -增加商品\n");
	printf("2 -进货\n");
	printf("========================\n");
	printf(">");
	scanf("%d", &user);

	if(user == 1)
	{
		printf("kind:");
		scanf("%s", kind);  
		getchar();
		printf("price:");
		scanf("%d", &price);
		getchar();
		printf("surplus:");
		scanf("%d", &surplus);
		getchar();

		sprintf(order, "insert into fruit values('%s', %d, %d, NULL, NULL)",kind, price, surplus);
		if(sqlite3_exec(fruit, order, NULL, NULL, &errmsg) != SQLITE_OK)
		{
			printf("Add kind:%s\n", errmsg);
		}
	}
	else if(user == 2)
	{
		printf("kind:");
		scanf("%s", kind);
		getchar();
		printf("surplus:");
		scanf("%d", &surplus);
		getchar();

		sprintf(order, "update fruit set surplus = %d where kind = '%s';", surplus, kind);
		if(sqlite3_exec(fruit, order, NULL, NULL, &errmsg) != SQLITE_OK)
		{
			printf("Add kind:%s\n", errmsg);
		}

		memset(order ,0, sizeof(order));
		now = time(NULL);   //得到进货时间
		tim = localtime(&now);

		sprintf(ti, "%04d-%02d-%02d", tim->tm_year+1900, tim->tm_mon+1, tim->tm_mday); 
		sprintf(order, "update fruit set purchase_time = '%s' where kind = '%s';", ti, kind);

		if(sqlite3_exec(fruit, order, NULL, NULL, &errmsg) != SQLITE_OK)
		{
			printf("time update: %s\n", errmsg);
		}

	}
	else
	{
		printf("input error!\n");
	}

}

void Decrease_fruit()
{
	int user = 0;
	char kind[20] = {0}, *errmsg, order[128] = {0}, ti[12] = {0};
	int surplus;
	time_t now;
	struct tm *tim;
	printf("========================\n");
	printf("1 -下架商品\n");
	printf("2 -出货\n");
	printf("========================\n");
	printf(">");
	scanf("%d", &user);
	if(user == 1)
	{
		printf("kind:");
		scanf("%s", kind);
		getchar();

		sprintf(order, "delete from fruit where kind = '%s';",kind);
		if(sqlite3_exec(fruit, order, NULL, NULL, &errmsg) != SQLITE_OK)
		{
			printf("delete kind:%s\n", errmsg);
		}
	}
	else if(user == 2)
	{
		printf("kind:");
		scanf("%s", kind);
		getchar();
		printf("surplus:");
		scanf("%d", &surplus);
		getchar();

		sprintf(order, "update fruit set surplus = %d where kind = '%s';", surplus, kind);
		if(sqlite3_exec(fruit, order, NULL, NULL, &errmsg) != SQLITE_OK)
		{
			printf("Add kind:%s\n", errmsg);
		}

		memset(order ,0, sizeof(order));
		now = time(NULL);
		tim = localtime(&now);

		sprintf(ti, "%04d-%02d-%02d", tim->tm_year+1900, tim->tm_mon+1, tim->tm_mday); 
		sprintf(order, "update fruit set shipping_time = '%s' where kind = '%s';", ti, kind);

		if(sqlite3_exec(fruit, order, NULL, NULL, &errmsg) != SQLITE_OK)
		{
			printf("time update: %s\n", errmsg);
		}

	}
	else
	{
		printf("input error!\n");
	}
}

void change_fruit()
{
	char kind[20] = {0}, *errmsg, order[128] = {0};
	int price;
	printf("========================\n");
	printf("更新商品价格!\n");
	printf("========================\n");
	printf("更新的商品>");
	scanf("%s", kind);
	getchar();
	printf("price:");
	scanf("%d", &price);
	getchar();
	sprintf(order, "update fruit set price = %d where kind = '%s';", price, kind);
	if(sqlite3_exec(fruit, order, NULL, NULL, &errmsg) != SQLITE_OK)
	{
		printf("update price:%s\n", errmsg);
	}
}

int callback(void* arg,int ncolumns ,char** f_value,char** f_name)
{
	int i;
if(key == 1)
{
	key = 0;
	for(i = 0; i < ncolumns; i++)
	{
		printf("%-15s ", f_name[i]);
	}
	putchar('\n');
}
	for(i = 0; i < ncolumns; i++)
	{
		printf("%-15s ", f_value[i]);
	}

	putchar('\n');

	return 0;
}

void look_fruit()
{
	char *errmsg, order[128] = {0};
	printf("========================\n");
	printf("查看商品\n");
	printf("========================\n");
	sleep(1);
	sprintf(order, "select * from fruit;");
	if(sqlite3_exec(fruit, order, callback, NULL, &errmsg) != SQLITE_OK)
	{
		printf("look:%s\n", errmsg);
	}
	key = 1;
}

int main(int argc, const char *argv[])
{
	/******数据库打开*******/
	char *errmsg;
	if(sqlite3_open(FRUIT, &fruit) != SQLITE_OK)
	{
		sqlite3_errmsg(fruit);
		exit(-1);
	}

	if(sqlite3_exec(fruit,"create table fruit(kind char, price Integer, surplus Integer, purchase_time char, shipping_time char);", NULL, NULL, &errmsg) != SQLITE_OK)
	{
		printf("fruit table :%s\n", errmsg);
	}

	while(1)
	{
		/*******判断操作者********/
		int user = 0;
		printf("========================\n");
		printf("1 -卖家进入\n");
		printf("2 -买家进入\n");
		printf("3 -退出\n");
		printf("========================\n");
		printf(">");
		scanf("%d", &user);
		getchar();

		if(user == 1)  //商家进入
		{
			sleep(1);
			printf("\n\n-------卖家已进入-------\n\n");
			sleep(1);

			printf("========================\n");
			printf("1 -进货\n");
			printf("2 -卖出\n");
			printf("3 -改价格\n");
			printf("4 -查看\n");
			printf("5 -退出\n");
			printf("========================\n");
			printf(">");
			scanf("%d", &user);
			getchar();

			switch(user)
			{
				case 1: Add_fruit();
						break;
				case 2: Decrease_fruit();
						break;
				case 3: change_fruit();
						break;
				case 4: look_fruit();
						break;
				case 5: break;
				default:
						break;
			}
		}
		else if(user == 2)  //买家进入
		{
			sleep(1);
			printf("\n\n-------买家已进入-------\n\n");
			sleep(1);
			look_fruit();
			
		}
		else if(user == 3)
		{
			sleep(1);
			printf("系统退出!\n");
			return 0;
		}
		else
		{
			printf("\ninput error!\n");
			sleep(1);
		}
	}
	return 0;
}

到这里就结束啦!
在这里插入图片描述

  • 22
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

修成真

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值