使用数据库实现增删改查

时间:2024-03-07 13:21:20

 

#include<myhead.h>

//定义添加数据函数

int do_add(sqlite3 *ppDb)
{
	//1.准备sql语句,输入要添加的信息
	int add_numb;          //工号
	char  add_name[20];    //姓名
	char  add_sex[10];     //性别
	double add_score;      //工资

	printf("请输入要添加的工号:");
	scanf("%d",&add_numb);
	printf("请输入要添加的姓名:");
	scanf("%s",add_name);
	printf("请输入要添加的性别:");
	scanf("%s", add_sex);
	printf("请输入要添加的工资:");
	scanf("%lf", &add_score);
	getchar();

	//准备sql语句
	char sql[128]="";
	sprintf(sql,"insert into Worker(numb, name, sex, score) value(%d,\"%s\",\"%s\",%2lf);",add_numb,add_name,add_sex,add_score);

	//2.定义错误信息存放指针
	char *errmsg = NULL;

	//3.执行语句
	if(sqlite3_exec(ppDb, sql, NULL,NULL,NULL, &errmsg) != SQLITE_OK)
	{
		printf("exec error:%s\n",errmsg);
		sqlite3_free(errmsg);
		errmsg = NULL;
		return -1;
	}
	printf("do_add success\n");
	return 0;
}

//删除员工信息
int do_delete(sqlite3 *ppDb)
{
	//1.准备sql语句 输入要删除员工信息
	int delete_numb;
	printf("请输入要删除记录的工号:");
	scanf("%d",&delete_numb);
	getchar();

	char sql[128]="";
	sprintff(sql,"delete from Stu where numb=%d",delete_numb);

	//2.定义错误信息存放指针
	char *errmsg = NULL;

	//3.执行语句

	if(sqlite3_exec(ppDb, sql, NULL,NULL,NULL, &errmsg) != SQLITE_OK)
	{
		printf("exec error:%s\n",errmsg);
		sqlite3_free(errmsg);
		errmsg = NULL;
		return -1;
	}
	printf("do_delete success\n");
	return 0;



}

int main(int argc, const char *argv[])
{
	//定义数据库句柄指针
	sqlite3 * ppDb = NULL;
	//打开数据库,如果数据库不存在,则创建数据库
	//将数据库句柄由参数2返回
	if(sqlite3_open("./my.db", &ppDb) != SQLITE_OK)
	{
		printf("sqlite3_open error,errcode=%d, errmsg = %s\n",\
				sqlite3_errcode(ppDb), sqlite3_errmsg(ppDb));
		return -1;
	}
	printf("sqlite3_open success\n");

	//创建数据表

	//1、准备sql语句
	char sql[128] = "create table if not exists Worker(numb int, name char, salary double)";
	//char *sql = "create table if not exists Worker(numb int, name char, salary double)";
	char *errmsg = NULL;       //存放执行sql语句口的错误信息
	if(sqlite3_exec(ppDb, sql, NULL, NULL, &errmsg) != SQLITE_OK)
	{
		printf("exec error : %s\n", errmsg);
		sqlite3_free(errmsg);             //防止内存泄露
		errmsg = NULL;
		return -1;
	}
	printf("员工信息表创建成功\n");

	int menu = -1;         //菜单选项
	for(;;)
	{
		system("clear");             //清空之前的终端信息
		printf("\t\t=======XXX公司员工管理系统=======\n");
		printf("\t\t======1、添加员工信息=========\n");
		printf("\t\t======2、删除员工信息=========\n");
		printf("\t\t======3、修改员工信息=========\n");
		printf("\t\t======4、查询员工信息=========\n");
		printf("\t\t======0、退出=========\n");

		printf("请输入操作码:");          //提示并输入信息
		scanf("%d", &menu);
		getchar();                          //吸收回车

		switch(menu)
		{
		case 1:
			{
				do_add(ppDb);
			}
			break;
		case 2:
			{
				do_delete(ppDb);
			}
			break;
		case 3:
			{
				//do_update(ppDb);
			}
			break;
		case 4:
			{
				//do_search(ppDb);
			}
			break;
		case 0:
			goto END;
		default:printf("您输入的功能有误,请重新输入!!!\n");
		}

		printf("请输入任意键,按回车清屏\n");
		while(getchar() != '\n');

	}




END:


	//关闭数据库
	sqlite3_close(ppDb);


	return 0;
}