#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
int ret = -1;
sqlite3 *db = NULL;
int callback(void *arg,int num,char **f_name,char **f_num)
{
static int count=0;
if(0==count)
{
for(int i=0;i<num;i++)
{
//表头
printf("%-15s",f_num[i]);
count=1;
}
printf("\n");
}
for(int i=0;i<num;i++)
{
printf("%-15s",f_name[i]);
}
printf("\n");
return 0;
}
//查看表
void show_table()
{
sqlite3_exec(db,"select *from ping_pong_sport;",callback,NULL,NULL);
}
//增加一行数据
void add_entry()
{
int age;
char name[20]={0};
char id[10]={0};
char sorce[10]={0};
printf("输入要添加的数据:('id','name','sorce',age):");
scanf("%s %s %s %d", id, name, sorce, &age);
char **result;
int row,column;
char *sql = malloc(1024);
snprintf(sql,100,"insert into ping_pong_sport values('%s','%s','%s',%d)",id,name,sorce,age);
sqlite3_get_table(db,sql,&result,&row,&column,NULL);
}
//删除一行数据
void delete_entry()
{
char name[20]={0};
printf("输入要删除数据的人的姓名:");
scanf("%s",name);
char *sql = malloc(100);
snprintf(sql,100,"delete from ping_pong_sport where name='%s'",name);
char **result;
int row,column;
sqlite3_get_table(db,sql,&result,&row,&column,NULL);
}
//修改一行数据的内容 先修改其中一个年龄
void change_entry()
{
char **result;
int row,column;
sqlite3_get_table(db,"update ping_pong_sport set age=17 where name='sunyingsha';",&result,&row,&column,NULL);
}
int main(int argc, const char *argv[])
{
//打开数据库
// sqlite3 *db = NULL;
ret = sqlite3_open("/home/ubuntu/sport.db",&db);
if(-1==ret)
{
printf("open database fail\n");
return -1;
}
int num;
printf("**********ping_pong_sport**********\n");
printf("choose the num to choose func:\n");
printf("1--bian li table\n");
printf("2--add a sport data\n");
printf("3--delete a sport data\n");
printf("4--change a sport data\n");
printf("***********************************\n");
scanf("%d",&num);
//对数据库进行操作 查看表
if(1==num)
{
show_table();
}
else if(2==num)
{
add_entry();
show_table();
}
else if(3==num)
{
delete_entry();
show_table();
}
else if(4==num)
{
change_entry();
show_table();
}
else
{
printf("输入错误 byebye\n");
return -1;
}
return 0;
}
实现数据库的增删改查
最新推荐文章于 2024-08-31 23:36:42 发布