C语言通过 sqlite3 的API进行开发

sqlite3除了可以通过命令行进行操作之外,还可以用接口函数进行开发,流程如下:

(1)新建、打开数据库文件,

int sqlite3_open(const char *filename,sqlite3 **ppDb);

返回值:成功返回SQLITE_OK,失败返回其他宏,具体可以查询sqlite3文件夹的头文件

参数:filename——路径名

          ppDB——数据库文件句柄

(2)数据库操作

 int sqlite3_exec(sqlite3*,char *sql,int (*callback)(void*,int,char**,char**),void *, char **errmsg);

返回值:成功返回SQLITE_OK,失败返回其他宏,具体可以查询sqlite3文件夹的头文件

参数:
sqlite3* ——数据库的句柄

sql ——你要执行的命令
int (*callback)(void*,int,char**,char**) ——函数指针
                                           作用:配合查询命令使用,当使用查询的时候必须传递这个参数

                                                     当执行查询命令的时候,查询的结果有几个,那么callback指向的函数就被调用几次
                                                 参数:void* ——要传递的任意值

                                                           int——表格中有多少字段(列数)
                                                           char**——存放每一行具体的信息
                                                           char** ——存放字段名
 void * ——传递给callback的第一个参数
errmsg——存 放出错信息的

(3)关闭数据库

int sqlite3_close(句柄);

注意:编译程序时需要指定sqlite3库的路径,头文件路径并链接库,参考命令如下:

gcc sqlitetest.c -o sqlitetest -I/home/win/sqlite3/include/ -L/home/win/sqlite3/lib/ -lsqlite3

具体例子如下:

#include <stdio.h>
#include "sqlite3.h"
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int showinfo(void *argc,int col,char **str1,char **str2)
{
	int i = 0;
	for(i=0; i<col; i++)
	{
		printf("%s:%s\n",*(str2+i),*(str1+i));
		if(i%col == 1)
			printf("\n");
	}

	return 0;
}

int main()
{
	int ret;
	char name[20];
	int age;
	sqlite3 *mydb;  //定义句柄

	//打开、新建数据库文件
	ret=sqlite3_open("./test.db",&mydb);
	if(ret!=SQLITE_OK)
	{
		printf("打开,新建数据库失败!\n");
		return -1;
	}
	//新建表格
	ret=sqlite3_exec(mydb,"create table student (name text,age int);",NULL,NULL,NULL);
	if(ret == 1)
		printf("the table is exist\n");
	
	else if(ret == SQLITE_OK)
		printf("建表成功\n");

	else
	{
		printf("新建表格失败!\n");
		return -1;
	}

	char order[70] ={};
	
	printf("请输入学生信息\n");
	printf("姓名:");
	scanf("%s",name);
	printf("年龄:");
	scanf("%d",&age);

	sprintf(order,"insert into student values(\"%s\",%d);",name,age);

	ret=sqlite3_exec(mydb,order,NULL,NULL,NULL);
	if(ret!=SQLITE_OK)
	{
		printf("加入数据失败!\n");
		return -1;
	}

	printf("加入数据成功\n");

	ret=sqlite3_exec(mydb,"select * from student;",showinfo,&ret,NULL);
	if(ret!=SQLITE_OK)
	{
		printf("加入数据失败!\n");
		return -1;
	}

	sqlite3_close(mydb);

	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章