1.关于sqlite的打开和创建
#include <stdio.h>
#include <sqlite3.h>
int main(int argc, char *argv[])
{
//打开或者创建数据库文件,得到数据库的句柄指针
sqlite3*db=NULL;
//SQLITE_OK==0
if(sqlite3_open("./yy.db",&db)!=SQLITE_OK)
{
//sqlite_errmsg(sqlite2*db):打印错误信息
printf("open:%s\n",sqlite3_errmsg(db));
return -1;
}
return 0;
}
2.关于sqlite的exec实现插入
#include <stdio.h>
#include <sqlite3.h>
int main(int argc, char *argv[])
{
//打开或者创建数据库文件,得到数据库的句柄指针
sqlite3*db=NULL;
//SQLITE_OK==0
if(sqlite3_open("./yy.db",&db)!=SQLITE_OK)
{
//sqlite_errmsg(sqlite2*db):打印错误信息
printf("open:%s\n",sqlite3_errmsg(db));
return -1;
}
//创建数据库表
char sql[128]="create table if not exists user(id integer primary key autoincrement,name text,sex varchar,age integer);";
//执行SQL语句
if(sqlite3_exec(db,sql,NULL,NULL,NULL)!=SQLITE_OK)
{
printf("%s\n",sqlite3_errmsg(db));
return -1;
}
char name[12]={0};
char sex;
int age;
scanf("%s %c %d",name,&sex,&age);
sprintf(sql,"insert into user(id,name,sex,age) values(NULL,'%s','%c','%d')",name,sex,age);
if(sqlite3_exec(db,sql,NULL,NULL,NULL)!=SQLITE_OK)
{
printf("insert:%s\n",sqlite3_errmsg(db));
return -1;
}
//关闭数据库
sqlite3_close(db);
return 0;
}
3.关于sqlite实现查询
#include <stdio.h>
#include <sqlite3.h>
//定义回调函数,查询结构有一条记录,就调用一次该函数
//p:传递给回调函数的参数
//f_num:保存一条记录的字段个数
//f_value:保存每个字段的数值(指针数组)
//f_name:保存字段的名字
int callback(void *p,int f_num,char **f_value,char **f_name)
{
printf("---------------\n");
for(int i=0;i<f_num;i++)
{
printf("%s: %s",f_value[i],f_name[i]);
}
printf("\n");
return 0;
}
int main(int argc, char *argv[])
{
//打开或者创建数据库文件,得到数据库的句柄指针
sqlite3*db=NULL;
//SQLITE_OK==0
if(sqlite3_open("./yy.db",&db)!=SQLITE_OK)
{
//sqlite_errmsg(sqlite2*db):打印错误信息
printf("open:%s\n",sqlite3_errmsg(db));
return -1;
}
char sql[128]="select * from user;";
if(sqlite3_exec(db,sql,callback,NULL,NULL)!=SQLITE_OK)
{
printf("select:%s\n",sqlite3_errmsg(db));
return -1;
}
//关闭数据库
sqlite3_close(db);
return 0;
}