以下是一个简单的数据库编程实例代码
#include <sqlite3.h>
#include <stdio.h>
typedef struct student
{
char name[32];
char sex[4];
int age;
double score;
}stu_t;
/********************************************************
* 函数名:callback
* 功 能:
* 处理找到的数据
* 参 数:
* arg:sqlite3_exec给函数的传参
* column:找到的这一条数据的列数(与SQL语句select后面选择的列数有关)
* pcontent:指针数组的数组名(指向该条数据每一列字符串首地址的指针数组)
* ptitle:指针数组的数组名(指向每一列名称字符串首地址的指针数组)
* 返回值:
* 成功返回0
* 失败返回-1
* 注意事项:
* 1.函数返回0成功,返回非0会使sqlite3_exec出错
* 2.每找到一条匹配的数据,则会调用一次callback,所以callback可能被调多次
********************************************************/
int callback(void *arg, int column, char** pcontent,char** ptitle)
{
int i = 0;
for (i = 0; i < column; i++)
{
printf("%s = %10s ", ptitle[i], pcontent[i]);
}
printf("\n");
return 0;
}
int main(void)
{
sqlite3 *pDb = NULL;
int ret = 0;
char cmdbuf[1024] = {0};
char *perrmsg = NULL;
stu_t s[3] = {
{"张三", "男", 19, 80},
{"李四", "女", 18, 60},
{"王二", "男", 20, 75},
};
int i = 0;
ret = sqlite3_open("student.db", &pDb);
if (ret != SQLITE_OK)
{
fprintf(stderr, "sqlite3_open failed! : %s\n", sqlite3_errmsg(pDb));
return -1;
}
sprintf(cmdbuf, "create table if not exists student(id integer primary key asc, name text, sex text, age integer, score double);");
ret = sqlite3_exec(pDb, cmdbuf, NULL, NULL, &perrmsg);
if (ret != SQLITE_OK)
{
fprintf(stderr, "sqlite3_exec failed! : %s\n", perrmsg);
sqlite3_free(perrmsg);
sqlite3_close(pDb);
return -1;
}
for (i = 0; i < 3; i++)
{
sprintf(cmdbuf, "insert into student values(NULL, \"%s\", \"%s\", %d, %lf);", s[i].name, s[i].sex, s[i].age, s[i].score);
ret = sqlite3_exec(pDb, cmdbuf, NULL, NULL, &perrmsg);
if (ret != SQLITE_OK)
{
fprintf(stderr, "sqlite3_exec failed! : %s\n", perrmsg);
sqlite3_free(perrmsg);
sqlite3_close(pDb);
return -1;
}
}
sprintf(cmdbuf, "select * from student;");
ret = sqlite3_exec(pDb, cmdbuf, callback, NULL, &perrmsg);
if (ret != SQLITE_OK)
{
fprintf(stderr, "sqlite3_exec failed! : %s\n", perrmsg);
sqlite3_free(perrmsg);
sqlite3_close(pDb);
return -1;
}
sqlite3_close(pDb);
return 0;
}