数据库操作的增、删、改完成
#include <myhead.h>//查询的回调函数
int callback(void* data,int count,char** argv, char** columnName)
{//count是字段数//argv是字段内容//columnName是字段名称for(int i=0;i<count;i++) {printf("%s=%s\n", columnName[i], argv[i] ? argv[i] : "NULL");}puts("");return 0;
}
int main(int argc, const char *argv[])
{//定义数据库句柄指针sqlite3 *ppfd=NULL;//打开一个数据库,如果不存在则创建并打开if(sqlite3_open("./my.db",&ppfd)!=SQLITE_OK){printf("sqlite3_open error,errcode\n");return -1;}puts("数据库打开成功");//创建数据表//1、准备sql1语句char sql1[128]="create table if not exists worker(id int,name char,salary double)";char *errmsg=NULL; //存放执行SQL语句中的错误信息if(sqlite3_exec(ppfd,sql1,NULL,NULL,&errmsg)!=SQLITE_OK){printf("exec error:%s\n",errmsg);sqlite3_free(errmsg);errmsg=NULL;return -1;}puts("员工信息表创建成功");int number; //操作码while(1){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", &number);getchar(); switch(number){case 1: //添加员工信息{//定义修改数据表中的数据容器char id[128]; //id char name[128]; //namechar salary[128]; //salaryprintf("请输入数据:");scanf("%s %s %s",id,name,salary);//准备sql2语句char sql2[128];sprintf(sql2,"insert into worker values (%s,'%s',%s)",id,name,salary);char *errmsg=NULL; //存放执行SQL语句中的错误信息if(sqlite3_exec(ppfd,sql2,NULL,NULL,&errmsg)!=SQLITE_OK){printf("exec error:%s\n",errmsg);sqlite3_free(errmsg);errmsg=NULL;return -1;}}break;case 2: //删除员工信息{char rbuf[128]; //字段名char sbuf[128]; //数据printf("请输入字段名和数据:");scanf("%s %s",rbuf,sbuf);//准备sql3语句char sql3[128];sprintf(sql3,"delete from worker where %s='%s'",rbuf,sbuf);printf("%s\n",sql3);char *errmsg=NULL; //存放执行SQL语句中的错误信息if(sqlite3_exec(ppfd,sql3,NULL,NULL,&errmsg)!=SQLITE_OK){printf("exec error:%s\n",errmsg);sqlite3_free(errmsg);errmsg=NULL;return -1;}}break;case 3: //修改员工信息{char rbuf[128]; //字段名char sbuf[128]; //数据char buf1[128]; //限制条件字段名char buf2[128]; //限制条件数据printf("请输入限制条件字段名和数据:");scanf(" %s %s",buf1,buf2);printf("修改的字段名和数据:");scanf(" %s %s",rbuf,sbuf);//准备sql4语句char sql4[128];sprintf(sql4,"update worker set %s='%s' where %s='%s'",rbuf,sbuf,buf1,buf2);char *errmsg=NULL; //存放执行SQL语句中的错误信息if(sqlite3_exec(ppfd,sql4,NULL,NULL,&errmsg)!=SQLITE_OK){printf("exec error:%s\n",errmsg);sqlite3_free(errmsg);errmsg=NULL;return -1;}}break;case 4: //查询员工信息{ char rbuf[128]; //字段名char sbuf[128]; //数据printf("查询的字段名和数据:");scanf(" %s %s",rbuf,sbuf);//准备sql5语句char sql5[128];sprintf(sql5,"select * from worker where %s='%s'",rbuf,sbuf);char *errmsg=NULL; //存放执行SQL语句中的错误信息if(sqlite3_exec(ppfd,sql5,callback,NULL,&errmsg)!=SQLITE_OK){printf("exec error:%s\n",errmsg);sqlite3_free(errmsg);errmsg=NULL;return -1;}}break;case 0:goto END;default:printf("您输入的功能有误,请重新输入!!!\n");}printf("请输入任意键,按回车清屏\n");while(getchar()!= '\n');}
END://关闭数据库sqlite3_close(ppfd);return 0;
}
sqlite_exec函数作业演示视频
思维导图