一个简单的使用sqlite3数据库的电话薄,很简单适合初学者看看,而且里面并没有很多容错处理很容易看懂的。
代码语言:javascript复制#include<stdio.h>
include"sqlite3.h"
static int callback(void notused,int l,char v,char lname);
int seek(sqlite3 db);
int insert(sqlite3 db);
int replace(sqlite3 db);
int del(sqlite3 db);
int option(sqlite3 db);
int quit(sqlite3 db);
int main()
{
int num;
int rc;
struct sqlite3 db;
rc=sqlite3_open("sql.db",&db);
if(rc)
{
printf("成功打开数据库");
}
else printf("数据库打开失败");
num=option(db);
quit(db);
}
int option(sqlite3 db)
{
int num;
int rc;
printf("t1.查询nt2.添加记录nt3.更新记录nt4.删除记录nt5.清屏nt6.创建表nt7.退出n");
printf("请输入:");
scanf("%d",&num);
switch (num)
{
case 1:seek(db);
break;
case 2:rc=insert(db);
break;
case 3:replace(db);
break;
case 4:del(db);
break;
case 5:
{
system("cls");
option(db);
}
case 6:
{
rc=sqlite3_exec(db,"CREATE TABLE telbook(name,telnum)",0,0,NULL);
printf("%dn",rc);
}
break;
case 7:{
printf("即将关闭n");
quit(db);
}
break;
default:
{ printf("请选择n");
option(db);
}
break;
}
}
int seek(sqlite3 db)
{
int num;
int rc;
char zSQL;
char sql_name[20],sql_telnum[11];
printf("t1.根据名字查找nt2.根据电话查找nt3.显示所有nt4.回上级目录");
scanf("%d",&num);
switch (num)
{
case 1:
{
printf("请输入名字:");
scanf("%s",sql_name);
zSQL= sqlite3_mprintf("select from telbook where name='%q'", sql_name);
rc=sqlite3_exec(db,zSQL,callback,0,NULL);
sqlite3_free(zSQL);
}
break;
case 2:
{
printf("请输入电话");
scanf("%s",sql_telnum);
zSQL= sqlite3_mprintf("select from telbook where telnum='%q'", sql_telnum);
rc=sqlite3_exec(db,zSQL,callback,0,NULL);
sqlite3_free(zSQL);
}
break;
case 3:rc=sqlite3_exec(db,"select from telbook",callback,0,NULL);
break;
case 4:option(db);
break;
default :
{ printf("请选择要执行的操作n");
option(db);
}
}
printf("%dn",rc);
option(db);
}
int insert(sqlite3 db)
{
int rc;
char sql_name[20],sql_telnum[11];
printf("输入姓名和电话以空格分隔:");
scanf("%s %s",sql_name,sql_telnum);
char zSQL;
zSQL= sqlite3_mprintf("INSERT INTO telbook VALUES('%q','%q')", sql_name,sql_telnum);
rc=sqlite3_exec(db,zSQL,0,0,NULL);
sqlite3_free(zSQL);
printf("%dn",rc);
option(db);
return 0;
}
int replace(sqlite3 db)
{
int rc;
char sql_name[20],sql_telnum[11];
printf("请输入名字和新电话号码:");
scanf("%s %s",sql_name,sql_telnum);
char zSQL;
zSQL= sqlite3_mprintf("update telbook set telnum='%q' where name='%q'", sql_telnum,sql_name);
rc=sqlite3_exec(db,zSQL,0,0,NULL);
sqlite3_free(zSQL);
printf("%dn",rc);
option(db);
return 0;
}
int del(sqlite3 db)
{
int rc;
char sql_name[20],sql_telnum[11];
printf("请输入要删除的姓名:");
scanf("%s",sql_name);
char zSQL;
zSQL= sqlite3_mprintf("DELETE FROM telbook where name='%q'", sql_name);
rc=sqlite3_exec(db,zSQL,0,0,NULL);
sqlite3_free(zSQL);
printf("%dn",rc);
option(db);
return 0;
}
int quit(sqlite3 db)
{ int rc;
rc=sqlite3_close(db);
if (rc)
{
printf("成功关闭数据库n");
}
else printf("关闭失败n");
system("pause");
exit(1);
}
static int callback(void notused,int l,char v,char lname)
{
int i;
for (i=0;i<l;i )
{
printf("%st",v[i]);
}
printf("n");
return 0;
}
</pre>