作业:完成数据库的增删改
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sqlite3.h>
void do_insert(sqlite3* sq,int id,char* name,float score)
{
char* errmsg=NULL;
char sql[1024]="";
printf("请输入学号、姓名、分数:");
scanf("%d %s %f",&id,name,&score);
getchar();
sprintf(sql, "insert into stu values(%d, '%s', %lf)", id, name, score);
if(sqlite3_exec(sq,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("插入失败\n");
printf("line:%d sqlite3_exec:%s\n",__LINE__,sqlite3_errmsg(sq));
}
else
{
printf("插入成功\n");
}
}
void do_delete(sqlite3* sq,int id)
{
char* errmsg=NULL;
char sql[1024]="";
printf("请输入要删除的信息的学号:");
scanf("%d",&id);
sprintf(sql,"delete from stu where id=%d",id);
if(sqlite3_exec(sq,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("删除失败\n");
printf("line:%d sqlite3_exec:%s\n",__LINE__,sqlite3_errmsg(sq));
}
else
{
printf("删除成功\n");
}
}
void do_update(sqlite3* sq,int id,float score)
{
char* errmsg=NULL;
char sql[1024]="";
printf("请输入要修改的信息和被修改信息的学号:");
scanf("%f %d",&score,&id);
sprintf(sql,"update stu set score=%f where id=%d",score,id);
if(sqlite3_exec(sq,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("修改失败\n");
printf("line:%d sqlite3_exec:%s\n",__LINE__,sqlite3_errmsg(sq));
}
else
{
printf("修改成功\n");
}
}
int main(int argc, const char *argv[])
{
sqlite3* sq=NULL;
if(sqlite3_open("./my.sq",&sq)!=SQLITE_OK)
{
printf("line:%d sqlite3_open:[%d] %s\n",__LINE__,sqlite3_errcode(sq),sqlite3_errmsg(sq));
return -1;
}
printf("sqlite3_open success\n");
char sql[128]="create table if not exists stu (id int,name char,score float)";
char* errmsg=NULL;
int id;
char* name;
float score;
if(sqlite3_exec(sq,sql,NULL,NULL,&errmsg)!=SQLITE_OK)
{
printf("line:%d sqlite3_exec:%s\n",__LINE__,errmsg);
return -1;
}
printf("create table stu success\n");
char c=0;
while(1)
{
printf("--------------------------\n");
printf("----------1.插入----------\n");
printf("----------2.删除----------\n");
printf("----------3.修改----------\n");
printf("----------4.查询----------\n");
printf("----------5.退出----------\n");
printf("--------------------------\n");
printf("请输入>>>");
c=getchar();
while(getchar()!=10);
switch(c)
{
case '1':
do_insert(sq,id,name,score);
break;
case '2':
do_delete(sq,id);
break;
case '3':
do_update(sq,id,score);
break;
case '4':
break;
case '5':
goto END;
break;
default:
printf("输入错误,请重新输入\n");
}
}
END:
if(sqlite3_close(sq)!=SQLITE_OK)
{
printf("line:%d sqlite3_close:%s\n",__LINE__,sqlite3_errmsg(sq));
return -1;
}
printf("sqlite3_close success\n");
sq=NULL;
return 0;
}
运行效果: