数据库连接池库libzdb使用教程

来源:互联网 发布:nginx 快速配置 编辑:程序博客网 时间:2024/05/21 01:48

Libzdb挺强大, 支持Mysql Oracle SQLite PostgreSQL,支持C和C++ Object C,不能在Window下用(看源码是因为基于Linux线程机制编写实现)。

遗憾的是找个资料太费劲,只能到Libzdb官网:点此进入 ,今正看着上面英文文档,突然网站就登不进去了,才发现国内论坛其实搜不出什么资料。

本文主要介绍Libzdb函数使用,帮理解英文文档有困难的朋友做下翻译。

库结构如下


首先下载libzdb的源码安装包,解压,在目录下执行./configure  make make install 安装。。以我自己为例,装完后再/usr/local/lib下有对应库文件

源码安装包  点此下载

线程池根据URL对象创建,URL对象通过char* 形式的URL生成,url中已经包含数据库类型,数据库名 用户密码等参数。形如:

database://[user:password@][host][:port]/database[?propertyName1][=propertyValue1]

MYSQL访问:

mysql://localhost:3306/test?user=root&password=swordfish
mysql://root:swordfish@localhost:3306/test

ORACLE访问:

oracle://localhost:1521/test?user=scott&password=tiger

oracle:///servicename?user=scott&password=tiger

SQLITE访问:

sqlite:///var/sqlite/test.db?synchronous=normal&heap_limit=8000&foreign_keys=on

PostgreSQL访问:

postgresql://root:swordfish@localhost/test?use-ssl=true

postgresql://localhost:5432/test?user=root&password=swordfish


2、

开启连接池

ConnectionPool_new(URL_T url) 根据URL生成连接池对象ConnectionPool_T,

ConnectionPool_start(ConnectionPool_T t); 开启数据库连接池(默认连接池大小为5),如果想自定义,需在开启前使用ConnectionPool_setInitialConnections函数设置。用法如下:

从数据库池中获取一个连接(此时活动连接+1):Connection_T ConnectionPool_getConnection (T P);

使用完毕后将连接放回连接池(此时活动连接-1):void  Connection_close (Connection_T C)

或者voidConnectionPool_returnConnection (T P, Connection_T connection)


3、

获取连接之后,执行数据库SQL语句

处T 代表 Connection_T , Connection_execute 用于执行数据库插入、更新、删除等操作。Connection_executeQuery用于数据库查询,返回结果集。


4、

游标移动至结果集下一行intResultSet_next (ResultSet_T R), 结果无下一行则返回false ,否则返回true。关于结果集其他操作函数如下


直接贴代码就好理解了:

#include<stdio.h>#include<stdlib.h>#include<string.h>#include<sys/types.h>#include<zdb/zdb.h>#include<zdb/Exception.h>#include<zdb/Connection.h>#include<zdb/URL.h>/* * 作者:搁浅的贝 * 编译方式:gcc main.c -I /usr/local/include/zdb/ -o main -lzdb  * */int main(int agc,char** argv){URL_T url = URL_new("mysql://localhost/AllinpayDB?user=root&password=root");if(url==NULL){printf("URL parse ERROR!\n");return 0;}ConnectionPool_T pool = ConnectionPool_new(url);//设置初始化连接数目ConnectionPool_setInitialConnections(pool,20);//开启线程池ConnectionPool_start(pool);//从线程池中取出连接(活动连接数+1)Connection_T con = ConnectionPool_getConnection(pool);//执行SQL语句,返回结果集ResultSet_T result = Connection_executeQuery(con, "select * from AlipayTrans");//输出全部连接数目printf("ALL NUMBE:%d\n",ConnectionPool_size(pool));//输出活动连接数目printf("ACTIVE NUMBER:%d\n",ConnectionPool_active(pool));while(ResultSet_next(result)) //游标滑到下一行{//获取列名 ResultSet_getColumnName//获取列值 ResultSet_getStringprintf("column: %s\n",ResultSet_getColumnName(result,2));//根据列名获取值ResultSet_getStringByNameprintf("%s\n ",ResultSet_getStringByName(result,"result_code"));//根据列索引获取列值 [注意索引是从1开始不是0]printf("%s\n ",ResultSet_getString(result,3));}//关闭连接(活动连接-1)Connection_close(con);//将连接池与数据库分离ConnectionPool_stop(pool);ConnectionPool_free(&pool);  URL_free(&url); return 0;}



0 0