数据库的创建,插入
#include <stdio.h>
#include <sqlite3.h>
void do_insert(sqlite3* db);
void do_delete(sqlite3* db);
void do_updata(sqlite3*db);
int main(int argc, const char *argv[])
{
sqlite3* db = NULL;
if(sqlite3_open("./stu.db", &db)!=SQLITE_OK)
{
fprintf(stderr, "__%d__sqlite3_open: %s\n",__LINE__, sqlite3_errmsg(db));
fprintf(stderr, "error_code:%d", sqlite3_errcode(db));
return -1;
}
printf("sqlite3 open success\n");
char sql[128] = "create table if not exists stu(id int , name char);";
char* errmsg = NULL;
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%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("请输入\n");
c = getchar();
while(getchar()!=10);
switch(c)
{
case '1':
do_insert(db);
break;
case '2':
do_delete(db);
break;
case '3':
do_updata(db);
break;
case '4':
//do_select();
break;
case '5':
goto END;
default:
printf("输入错误请重新输入\n");
}
}
END:
if(sqlite3_close(db)!= SQLITE_OK)
{
fprintf(stderr, "__%d__sqlite3_open: %s\n",__LINE__, sqlite3_errmsg(db));
fprintf(stderr, "error_code:%d", sqlite3_errcode(db));
return -1;
}
return 0;
}
void do_insert(sqlite3* db)
{
char sql[128]="";
char str[20]="";
int c;
printf("请输入要插入的id和名字>>");
scanf("%d %s", &c, str);
while(getchar()!=10);
sprintf(sql, "insert into stu values(%d , '%s');",c, str);
char* errmsg = NULL;
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__sqlite3_exec: %s\n", __LINE__, errmsg);
return ;
}
printf("insert table stu success\n");
}
void do_delete(sqlite3* db)
{
char sql[128]="";
char str[20]="";
int c;
printf("请输入要删除的id号>>");
scanf("%d", &c);
while(getchar()!=10);
sprintf(sql, "delete from stu where id=%d;",c);
char* errmsg = NULL;
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__sqlite3_exec: %s\n", __LINE__, errmsg);
return ;
}
printf("delete table stu success\n");
}
void do_updata(sqlite3*db)
{
char sql[128]="";
char str[20]="";
int c;
printf("请输入id号和修改名字>>");
scanf("%d %s", &c, str);
while(getchar()!=10);
sprintf(sql, "update stu set name='%s' where id= %d;", str,c);
char* errmsg = NULL;
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__sqlite3_exec: %s\n", __LINE__, errmsg);
return ;
}
printf("update table stu success\n");
}