#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
#include <string.h>
void do_insert(sqlite3*,char*);
void do_delete(sqlite3*,char*);
void do_updata(sqlite3* db,char* errmsg);
int main(int argc, const char *argv[])
{
//创建并打开数据库
sqlite3 *db=NULL;
if(sqlite3_open("./my.db",&db)!=SQLITE_OK){
printf("line:%d errno:%s\n",__LINE__,sqlite3_errmsg(db));
return -1;
}
printf("database open success\n");
//创建一张表格
char sql[128]="create table if not exists stu (id int PRIMARY KEY,name char,score float);";
char* errmsg=NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=SQLITE_OK){
fprintf(stderr,"line:%d sqlite3_exec:%s\n",__LINE__,errmsg);
return -1;
}
printf("create table success\n");
char c =0;
while(1){
system("clear");
printf("------------------------\n");
printf("----------1.增----------\n");
printf("----------2.删----------\n");
printf("----------3.改----------\n");
printf("----------4.查----------\n");
printf("----------5.退----------\n");
printf("------------------------\n");
printf("请输入:\n");
c=getchar();
while(getchar()!=10);
switch(c){
case '1':
do_insert(db,errmsg);
break;
case '2':
do_delete(db,errmsg);
break;
case '3':
do_updata(db,errmsg);
break;
case '4':
break;
case '5':
goto END;
default:
printf("输入错误,请重新输入\n");
}
printf("输入任意字符清屏\n");
while(getchar()!=10);
}
END:
if(sqlite3_close(db)!=SQLITE_OK){
fprintf(stderr,"line:%d sqlite3_exec:%s\n",__LINE__,sqlite3_errmsg(db));
return -1;
}
printf("database close success\n");
return 0;
}
void do_insert(sqlite3* db,char* errmsg){
int id=0;
char name[10]={0};
float score=0;
char buf[128]={0};
bzero(buf,sizeof(buf));
scanf("%d %s %f",&id,name,&score);
sprintf(buf,"insert into stu values (%d,'%s',%f)",id,name,score);
sqlite3_exec(db,buf,NULL,NULL,&errmsg);
}
void do_delete(sqlite3* db,char* errmsg){
int id=0;
char buf[128]={0};
scanf("%d",&id);
sprintf(buf,"delete from stu where id = %d",id);
sqlite3_exec(db,buf,NULL,NULL,&errmsg);
}
void do_updata(sqlite3* db,char* errmsg){
int id=0;
char buf[128]={0};
float score=0;
scanf("%d %f",&id,&score);
sprintf(buf,"update stu set score=%f where id=%d",score,id);
sqlite3_exec(db,buf,NULL,NULL,&errmsg);
}
完成数据库的增删改
最新推荐文章于 2024-08-16 18:39:05 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)