#include <myhead.h>//定义添加员工信息函数
int Add_worker(sqlite3 *ppDb)
{//准备sql语句printf("请输入要添加的员工信息:\n");//从终端获取员工信息char rbuf[128]="";fgets(rbuf,sizeof(rbuf),stdin);rbuf[strlen(rbuf)-1]=0;char sql[128]="insert into worker values";strcat(sql,rbuf);//存放执行sql语句后的错误信息char *errmsg=NULL;if(sqlite3_exec(ppDb,sql,NULL,NULL,&errmsg) != SQLITE_OK){printf("exec error:%s\n",errmsg);sqlite3_free(errmsg); //防止内存泄露errmsg=NULL;return -1;}return 0;
}//定义删除员工信息函数
int del_worker(sqlite3 *ppDb)
{//准备sql语句int numb;printf("请输入要删除的员工工号:");scanf("%d",&numb);char sql[128]="";sprintf(sql,"delete from worker where numb=%d;",numb);//存放执行sql语句后的错误信息char *errmsg=NULL;if(sqlite3_exec(ppDb,sql,NULL,NULL,&errmsg) != SQLITE_OK){printf("exec error:%s\n",errmsg);sqlite3_free(errmsg); //防止内存泄露errmsg=NULL;return -1;}return 0;
}//定义修改员工信息函数
int modify_worker(sqlite3 *ppDb)
{//准备sql语句int numb;double salary;printf("请输入要修改的员工工号:");scanf("%d",&numb);getchar();printf("请输入要修改的工资:");scanf("%lf",&salary);getchar();char sql[128]="";sprintf(sql,"update worker set salary=%lf where numb=%d;",salary,numb);//存放执行sql语句后的错误信息char *errmsg=NULL;if(sqlite3_exec(ppDb,sql,NULL,NULL,&errmsg) != SQLITE_OK){printf("exec error:%s\n",errmsg);sqlite3_free(errmsg); //防止内存泄露errmsg=NULL;return -1;}return 0;
}/**********************************主程序***************************************/
int main(int argc, const char *argv[])
{//定义数据库句柄sqlite3 *ppDb=NULL;//打开数据库,不存在则创建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");//创建数据表//准备sql语句char sql[128]="create table if not exists worker(numb int,name char,salary double)";//存放执行sql语句后的错误信息char *errmsg=NULL;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; //菜单选项while(1){system("clear"); //清屏printf("\t\t*********员工管理系统*********\n");printf("\t\t*********1.添加员工信息*********\n");printf("\t\t*********2.删除员工信息*********\n");printf("\t\t*********3.修改员工信息*********\n");printf("\t\t*********0.退出管理系统*********\n");printf("请输入选项>>>");scanf("%d",&menu);getchar();switch(menu){case 1:{//添加员工信息Add_worker(ppDb);}break;case 2:{//删除员工信息del_worker(ppDb);}break;case 3:{//修改员工信息modify_worker(ppDb);}break;case 0://退出管理系统goto END;break;default:printf("输入的选项有误,请重新输入\n");break;}printf("按任意键清屏\n");while(getchar()!='\n');}
END://关闭数据库sqlite3_close(ppDb);return 0;
}