1、数据库的增删改
#include <myhead.h>
int main(int argc, const char *argv[])
{
//定义数据库句柄指针
sqlite3 *kdb=NULL;
//打开数据库,不存在则创建
if(sqlite3_open("./my.db",&kdb)!=SQLITE_OK)
{
printf("sqlite3_open error\n");
return -1;
}
printf("sqlite3_open success\n");
//创建数据表
//准备sql语句
char sql[128]="create table if not exists worker(id double,name char,salary double)";
char *errmsg=NULL;//存放执行sql语句的错误信息
if(sqlite3_exec(kdb,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("exec error:%s\n",errmsg);
sqlite3_free(errmsg);//防止内存泄露
errmsg=NULL;
return -1;
}
//增删改查
int key=-1;
while(1)
{
printf("\t\t\t==信息表==\n");
printf("\t\t1、插入信息\n");
printf("\t\t2、删除信息\n");
printf("\t\t3、修改信息\n");
printf("\t\t4、退出\n");
scanf("%d",&key);
int id=0;;
char name[10]="";
int salary=0;;
switch(key)
{
case 1:
{
printf("please enter id:");
scanf("%d",&id);
printf("please enter name:");
scanf("%s",name);
printf("please enter salary:");
scanf("%d",&salary);
char sq1[128]="";
sprintf(sq1,"insert into worker(id,name,salary) values(%d,'%s',%d)",id,name,salary);
if(sqlite3_exec(kdb,sq1,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("add error\n");
sqlite3_free(errmsg);//防止内存泄露
errmsg=NULL;
return -1;
}
printf("add success\n");
}
break;
case 2:
{
printf("please enter id to delete:");
scanf("%d",&id);
char sq2[128]="";
sprintf(sq2,"delete from worker where id=%d",id);
if(sqlite3_exec(kdb,sq2,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("delete error\n");
sqlite3_free(errmsg);//防止内存泄露
errmsg=NULL;
return -1;
}
printf("delete success\n");
}
break;
case 3:
{
int n=-1;
printf("please enter 1 to modify id,2 to modify name,3 to modify salary\n");
scanf("%d",&n);
if(n==1)
{
int oldid=0;
printf("please enter old id:");
scanf("%d",&oldid);
printf("please enter new id:");
scanf("%d",&id);
char sq3[128]="";
sprintf(sq3,"update worker set id=%d where id=%d",id,oldid);
if(sqlite3_exec(kdb,sq3,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("modify error\n");
sqlite3_free(errmsg);//防止内存泄露
errmsg=NULL;
return -1;
}
printf("modify success\n");
}
if(n==2)
{
printf("please enter id:");
scanf("%d",&id);
printf("please enter new name:");
scanf("%s",name);
char sq4[128]="";
sprintf(sq4,"update worker set name='%s' where id=%d",name,id);
if(sqlite3_exec(kdb,sq4,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("modify error\n");
sqlite3_free(errmsg);//防止内存泄露
errmsg=NULL;
return -1;
}
printf("modify success\n");
}
if(n==3)
{
printf("please enter id:");
scanf("%d",&id);
printf("please enter new salary:");
scanf("%d",&salary);
char sq5[128]="";
sprintf(sq5,"update worker set salary=%d where id=%d",salary,id);
if(sqlite3_exec(kdb,sq5,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("modify error\n");
sqlite3_free(errmsg);//防止内存泄露
errmsg=NULL;
return -1;
}
printf("modify success\n");
}
}
break;
}
if(key==4)
{
printf("退出成功\n");
break;
}
}
//关闭数据库
sqlite3_close(kdb);
return 0;
}
2、思维导图