安装Berkeley DB

来源:互联网 发布:redis mysql 架构 编辑:程序博客网 时间:2024/06/08 15:10

Berkeley DB是由美国Sleepycat Software公司开发的一套开放源代码的嵌入式数据库管理系统(已被Oracle收购),它为应用程序提供可伸缩的、高性能的、有事务保护功能的数据管理服务。

Berkeley DB为许多编程语言提供了实用的api接口,包括c、c++、java、perl、tcl、python和php等。所有同数据库相关的操作都由Berkeley DB函数库负责统一完成。

官方地址为:http://www.oracle.com/technology/products/berkeley-db/db/index.html

本文就先讲一下如何在CentOS下安装Berkeley DB数据库(其他系统类似)。

1、安装Berkeley DB

# cd /usr/local/src# wget http://download.oracle.com/berkeley-db/db-4.6.18.tar.gz# tar -zxvf db-4.6.18.tar.gz# cd db-4.6.18# cd build_unix

Berkeley DB默认是安装在/usr/local/BerkeleyDB.4.6目录下,其中4.6就是版本号,你也可以指定–prefix参数来设置安装目录。

# ../dist/configure --prefix=/usr/local/berkeleydb --enable-cxx

其中–enable-cxx就是编译C++库,这样才能编译Berkeley DB数据库的PHP扩展php_db4。

# make# make install
# echo '/usr/local/berkeleydb/lib/' >> /etc/ld.so.conf# ldconfig

这2句的作用就是通知系统Berkeley DB的动态链接库在/usr/local/berkeleydb/lib/目录。

至此,Berkeley DB数据库已经安装完成。

2、安装Berkeley DB的PHP扩展
虽然PHP里已经自带了php_db和php_dba两个扩展都支持Berkekey DB,但是毕竟支持的有限,所以还是编译Berkeley DB自带的php_db4扩展好。

# cd /usr/local/src/db-4.6.18/php_db4/# phpize# ./configure --with-db4=/usr/local/berkeleydb/# make# make install

至此db4已编译好在/usr/lib64/php/modules/db4.so目录(具体跟你的系统有关)

修改php.ini 文件

添加:

extension=db4.so

重起WEB服务器(Apache等)
至此php_db4扩展的安装也完成了,执行php -m即可看到db4扩展已经加载了。


从字面上也不难理解,Db4Env设置数据库环境、Db4操作数据库、Db4Txn用于事务处理、Db4Cursor用于光标处理。具体使用可参考

php的函数参考:安装包的源码

c的参考函数:http://www.oracle.com/technology/documentation/berkeley-db/db/api_cxx/frame.html

/usr/local/src/db-4.6.18/php_db4/samples目录下提供了2个简单的例子simple_counter.php和transactional_counter.php。

simple_counter.php

<?php// Create a new Db4 Instance$db = new Db4(); // Open it outside a Db4Env environment with datafile/var/lib/db4 // and database name "test"$db->open(null, "/var/tmp/db4", "test"); // Get the current value of "counter"$counter = $db->get("counter");print "Counter Value is $counter\n"; // Increment $counter and put() it.$db->put("counter", $counter+1);// Sync to be certain, since we're leaving the handle open$db->sync();?>

transactional_counter.php

<?php// Open a new Db4Env$dbenv = new Db4Env();$dbenv->set_data_dir("/var/tmp/dbhome");$dbenv->open("/var/tmp/dbhome"); // Open a database in $dbenv.  Note that even though// we pass null in as the transaction, db4 forces this// operation to be transactionally protected, so PHP// will force auto-commit internally.$db = new Db4($dbenv);$db->open(null, 'a', 'foo'); $counter = $db->get("counter");// Create a new transaction$txn = $dbenv->txn_begin();if($txn == false) {  print "txn_begin failed";  exit;}print "Current value of counter is $counter\n"; // Increment and reset counter, protect it with $txn$db->put("counter", $counter+1, $txn); // Commit the transaction, otherwise the above put() will rollback.$txn->commit();// Sync for good measure$db->sync();// This isn't a real close, use _close() for that.$db->close();?>