作业要求:数据库操作的增、删、改
程序代码:
#include<myhead.h>
int main(int argc, const char *argv[])
{//定义数据库句柄指针sqlite3 * ppDb = NULL;//打开数据库,如果数据库不存在,则创建数据库//将数据库句柄由参数2返回if(sqlite3_open("./stu.db",&ppDb) != 0){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 *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======公司员工管理系统======\n");printf("\t\t======1.添加员工信息======\n");printf("\t\t======2.删除员工信息======\n");printf("\t\t======3.修改员工信息======\n");printf("\t\t======4.查询员工信息======\n");printf("\t\t======5.退出======\n");printf("请输入操作码:"); //提示并输入信息scanf("%d",&menu);getchar(); //吸收回车switch(menu){case 1:{char ch[64];char *errmsg = NULL;printf("请按照格式输入: (numb,'name',salary)\n");fgets(ch,sizeof(ch),stdin);char buf[128] = "insert into worker values";strcat(buf,ch);if(sqlite3_exec(ppDb , buf , NULL , NULL , &errmsg) != SQLITE_OK){printf("insert error : %s\n",errmsg);sqlite3_free(errmsg); //防止内存泄漏errmsg = NULL;return -1;}printf("员工信息添加成功\n");}break;case 2:{char ch[64];char *errmsg = NULL;printf("请按照格式输入: 'name'\n");fgets(ch,sizeof(ch),stdin);char buf[128] = "delete from worker where name=";strcat(buf,ch);if(sqlite3_exec(ppDb , buf , NULL , NULL , &errmsg) != SQLITE_OK){printf("delete error : %s\n",errmsg);sqlite3_free(errmsg); //防止内存泄漏errmsg = NULL;return -1;}printf("员工信息删除成功\n");}break;case 3:{for(;;){system("clear"); //清空之前的终端信息printf("\t\t======修改员工信息======\n");printf("\t\t======1.修改员工numb信息======\n");printf("\t\t======2.修改员工salary信息======\n");printf("\t\t======3.退出======\n");printf("请输入操作码:"); //提示并输入信息scanf("%d",&menu);getchar(); //吸收回车switch(menu){case 1:{char ch[64];char *errmsg = NULL;printf("请按照格式输入:numb where name='name'\n");fgets(ch,sizeof(ch),stdin);char buf[128] = "update worker set numb=";strcat(buf,ch);if(sqlite3_exec(ppDb , buf , NULL , NULL , &errmsg) != SQLITE_OK){printf("update error : %s\n",errmsg);sqlite3_free(errmsg); //防止内存泄漏errmsg = NULL;return -1;}printf("员工numb信息修改成功\n");}break;case 2:{char ch[64];char *errmsg = NULL;printf("请按照格式输入:salary where name='name'\n");fgets(ch,sizeof(ch),stdin);char buf[128] = "update worker set salary=";strcat(buf,ch);if(sqlite3_exec(ppDb , buf , NULL , NULL , &errmsg) != SQLITE_OK){printf("update error : %s\n",errmsg);sqlite3_free(errmsg); //防止内存泄漏errmsg = NULL;return -1;}printf("员工salary信息修改成功\n");}break;case 3:goto end;}}}break;
end:break;case 4:{//查找员工信息}break;case 5:goto END;default:printf("您输入的功能有误,请重新输入!!!\n");}printf("请输入任意键,按回车清屏\n");while(getchar() != '\n');}
END://关闭数据库sqlite3_close(ppDb);return 0;
}
运行结果:
添加员工信息:
删除员工信息:
修改员工信息:
总运行结果:
课程总结: