#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
int do_insert(sqlite3 *db);
int do_delete(sqlite3 *db);
int do_change(sqlite3 *db);
int main(int argc, const char *argv[])
{
char choose;
sqlite3* db=NULL;
if(sqlite3_open("./my.db",&db)!=SQLITE_OK)
{
fprintf(stderr,"sqlite3_open falied :%d %s\n",sqlite3_errcode(db),sqlite3_errmsg(db));
return -1;
}
printf("database open success");
char sql[128]="create table if not exists stu1(name char primary key,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("table create success\n");
while(1)
{
system("clear");
printf("-----------------------\n");
printf("--------1.插入-------\n");
printf("--------2.删除-------\n");
printf("--------3.修改-------\n");
printf("--------4.查询-------\n");
printf("--------5.退出-------\n");
printf("-----------------------\n");
choose=getchar();
while(getchar()!=10);
switch(choose)
{
case '1':
do_insert(db);
break;
case '2':
do_delete(db);
break;
case '3':
do_change(db);
break;
case '4':
break;
case '5':
goto END;
break;
default:
break;
}
}
END:
if(sqlite3_close(db)!=SQLITE_OK)
{
fprintf(stderr,"line:%d sqlite3_close:%d %s\n",__LINE__,sqlite3_errcode(db),sqlite3_errmsg(db));
return -1;
}
return 0;
}
int do_insert(sqlite3 *db)
{
char name1[20];
float score1;
printf("请输入姓名:\n");
scanf("%s",name1);
printf("请输人成绩\n");
scanf("%f",&score1);
char sql[128]="";
sprintf(sql,"insert into stu1 values('%s',%f);",name1,score1);
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;
}
return 0;
}
int do_delete(sqlite3 *db)
{
char name1[20];
printf("请输入要删除的学生姓名\n");
scanf("%s",name1);
char sql[128]="";
sprintf(sql,"delete from stu1 where name='%s'",name1);
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;
}
return 0;
}
int do_change(sqlite3 *db)
{ char name1[20];
float score1;
printf("请输入要更改信息的学生姓名:\n");
scanf("%s",name1);
printf("请输入更改后的学生成绩:\n");
scanf("%f",&score1);
char sql[128]="";
sprintf(sql,"update stu1 set score=%f where name='%s'",score1,name1);
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;
}
return 0;
}