libzdb c语言的数据库连接池支持库 源码分析
Standard整个程序可以支持各种数据库,是通过“接口实现的”。
而C语言并没有接口的概念,它是如何实现的呢?
在ConnectionDelegate.h文件里定义了一个结构体,这个结构体是保存一个数据库连接的所有信息和操作方法,这里的方法都是使用函数指针来定义的。
而在每种数据库实现时,使用这种结构体定义时,分别赋予了每种数据库对应的函数操作方法,这样就实现了接口的定义。
结构体中虽然存储的是数据,但是这个数据如果是指针类型,那么他的作用就不仅仅能够赋值了。这里的“接口”,实质就是对函数指针的灵活运用。
使用方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//首先初始化数据库连接池
URL_T url
= URL_new("mysql://localhost/test?user=root&password=swordfish");
//设置连接url
ConnectionPool_T
pool =
ConnectionPool_new(url);
//新建一个连接池结构体,并分配内存
ConnectionPool_start(pool);
//初始化连接池(建立连接),调用fillpool
//...
Connection_T con
= ConnectionPool_getConnection(pool);
//从连接池获取一个连接
ResultSet_T
result =
Connection_executeQuery(con,
"select id, name, image from employee where salary>%d",
anumber);
//使用此连接执行查询数据操作
while (ResultSet_next(result))
{
int
id =
ResultSet_getInt(result,
1);
const
char *name
= ResultSet_getString(result,
2);
int
blobSize;
const
void *image
= ResultSet_getBlob(result,
3,
&blobSize);
//...
}
Connection_close(con);
//连接使用完关闭连接
//...
ConnectionPool_free(&pool);
//关闭连接池
URL_free(&url);
|