Home Article sqlite3增删查改C语言程序

sqlite3增删查改C语言程序

Release time:2020-08-20 23:30:45 Author:admin Reading volume:135

 

 

 

 增删查改.c

#include
#include
#include
 
#define DATABASE "stu.db"
 
int do_insert(sqlite3 *db)
{
int id;
char name[32] = {0};
int score;
char sql[128] = {0};
char *errmsg;
 
printf("input id:");
scanf("%d",&id);
getchar();
printf("input name:");
scanf("%s",name);
getchar();
printf("input score:");
scanf("%d",&score);
getchar();
 
sprintf(sql,"insert into stu values(%d, '%s', %d);",id , name, score);
 
if (sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
{
printf("%s ",errmsg);
}
else
{
printf("insert success! ");
}
 
}
 
int do_delete(sqlite3 *db)
{
int id;
char sql[128] = {0};
char *errmsg;
 
printf("input id:");
scanf("%d",&id);
getchar();
 
sprintf(sql,"delete from stu where id = %d;",id);
 
if (sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
{
printf("%s ",errmsg);
}
else
{
printf("delete success! ");
}
 
}
int do_update(sqlite3 *db)
{
int id;
char sql[128] = {0};
int score;
char *errmsg;
 
printf("input id:");
scanf("%d",&id);
getchar();
 
printf("update score:");
scanf("%d",&score);
getchar();
 
 
sprintf(sql,"update stu set score = %d where id = %d",score,id);
 
if (sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
{
printf("%s ",errmsg);
}
else
{
printf("update success! ");
}
}
int callback(void *para, int f_num, char **f_value, char **f_name)
{
int i = 0;
for (i =0 ; i<f_num; i++)
{
printf("%-11s ",f_value[i]);
}
printf(" ");
 
 
return 0;
}
 
int do_query(sqlite3 *db)
{
char sql[128]={0};
char *errmsg;
 
sprintf(sql,"select * from stu;");
if (sqlite3_exec(db,sql,callback,NULL,&errmsg) != SQLITE_OK)
{
printf("%s ",errmsg);
}
else
{
printf("query success! ");
}
}
 
int main(int argc, char *argv[])
{
sqlite3 *db;
char *errmsg;
int cmd;
//打开表
if (sqlite3_open(DATABASE, &db) != SQLITE_OK)
{
printf("%s ",sqlite3_errmsg(db));
return -1;
}
else
{
printf("open database success! ");
}
 
//创建表
if (sqlite3_exec(db,"create table stu(id integer, name char, score integer);", NULL, NULL, &errmsg) != SQLITE_OK)
{
printf("%s ",errmsg);
}
else
{
printf("create table success! ");
}
while(1)
{
printf("------------------------------------------ ");
printf("1:insert 2:delete 3:query 4:update 5:quit ");
printf("------------------------------------------ ");
 
scanf("%d",&cmd);
getchar;
 
switch(cmd)
{
case 1:
do_insert(db);
break;
case 2:
do_delete(db);
break;
case 3:
do_query(db);
break;
case 4:
do_update(db);
break;
case 5:
sqlite3_close(db);
exit(0);
default:
printf("error cmd. ");
}
}
return 0;
 
}

 

 

支付宝打赏 微信打赏
  
I want to comment

Search

Leave a message
http://blog.rjxj513.com/
User login
You have not written any reviews yet!
You have commented!
Can only praise once!
You have a collection!