实现代码如下
#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
#include <string.h>
//回调函数
int callback(void *arg,int num,char **f_name,char **f_num)//char **f_name, char *f_name[]
{ //数据个数,//每一个数据,//每一个表头
static int flag = 0;
if(flag == 0)
{
//打印查询结果
for(int i = 0;i < num;i++)
{
printf("%-10s",f_num[i]);
}
flag = 1;
printf("\n");
}
return 0;
}
int main()
{
//1.打开数据库
sqlite3 *db = NULL;
sqlite3_open("./owner.db",&db);
printf("欢迎进入车主数据库\n");
printf("1.查询数据\n2.增加数据\n3.修改数据\n4.删除数据\n");
printf("请输入要执行的操作提示:\n");
int tip,row,column;
scanf("%d",&tip);
getchar();
char *sql = malloc(1024);
char **result;
char *buf = malloc(100);
char *buf1 = malloc(100);
/***********查询操作*********/
if(tip==1)
{
printf("请输入要查询的表名(owner):\n");
//把键盘输入和sql命令拼接
fgets(buf,100,stdin);
if(strcmp(buf,"owner\n")==0)
{
printf("该表有以下字段\n");
sqlite3_exec(db, "select *from owner;",&callback, NULL, NULL);
printf("请输入要查询的列名:\n");
fgets(buf,100,stdin);
buf[strcspn(buf,"\n")]=0;
snprintf(sql,1024,"select %s from owner;",buf);
printf("sql=%s\n",sql);
sqlite3_get_table(db,sql,&result, &row,&column,NULL);
for(int i = 0;i <(row+1)*column;i++)
{
printf("%-18s",result[i]);
if((i+1)%column == 0)
{
printf("\n");
}
}
}
}
/***********增加数据************/
if(tip==2)
{
printf("请输入要增加数据的表名(owner):\n");
//把键盘输入和sql命令拼接
fgets(buf,100,stdin);
if(strcmp(buf,"owner\n")==0)
{
printf("该表有以下字段\n");
sqlite3_exec(db, "select *from owner;",&callback, NULL, NULL);
printf("请输入要增加的数据:\n");
fgets(buf,100,stdin);
buf[strcspn(buf,"\n")]=0;
snprintf(sql,1024,"insert into owner values(%s);",buf);
printf("sql=%s\n",sql);
sqlite3_exec(db, sql,NULL, NULL, NULL);
}
}
/***********修改数据***********/
if(tip==3)
{
printf("请输入要修改数据的表名(owner):\n");
//把键盘输入和sql命令拼接
fgets(buf,100,stdin);
if(strcmp(buf,"owner\n")==0)
{
printf("该表有以下字段\n");
sqlite3_exec(db, "select *from owner;",&callback, NULL, NULL);
printf("请输入要修改的数据:\n");
fgets(buf,100,stdin);
buf[strcspn(buf,"\n")]=0;
printf("请输入修改的条件:\n");
fgets(buf1,100,stdin);
buf1[strcspn(buf1,"\n")]=0;
snprintf(sql,1024,"update owner set %s where %s;",buf,buf1);
printf("sql=%s\n",sql);
sqlite3_exec(db, sql,NULL, NULL, NULL);
}
}
/***********删除数据************/
if(tip==4)
{
printf("请输入要删除数据的表名(owner):\n");
//把键盘输入和sql命令拼接
fgets(buf,100,stdin);
if(strcmp(buf,"owner\n")==0)
{
printf("该表有以下字段\n");
sqlite3_exec(db, "select *from owner;",&callback, NULL, NULL);
printf("请输入要删除数据的条件:\n");
fgets(buf1,100,stdin);
buf1[strcspn(buf1,"\n")]=0;
snprintf(sql,1024,"delete from owner where %s;",buf1);
printf("sql=%s\n",sql);
sqlite3_exec(db, sql,NULL, NULL, NULL);
}
}
}
运行结果:
查:
增:
改:
删: