设为首页 加入收藏

TOP

Postgres访问其他PostgresQL数据库的功能DBLINK
2014-11-24 00:04:33 来源: 作者: 【 】 浏览:5
Tags:Postgres 访问 其他 PostgresQL 数据库 功能 DBLINK

Postgres访问其他PostgresQL 数据库的功能DBLINK
有时候的业务需要参照其他数据库的数据。
我们可以在程序中分别从两个数据库中取值然后处理。但这样开发效率和性能都不是很好。
如果两个数据库都是PostgreSQL的话,用扩展的DBLINK功能非常简单。
比如一个数据db1,db2。首先需要把db1加入dblink扩展。
示例1:取得db2的用户表的用户名 www.2cto.com
SELECT * FROM dblink('hostaddr=192.168.0.222 port=5432 dbname=db2 user=postgres password=postgres',
'SELECT user_name From people') AS t(user_name text);
如果认为每次查询都要写dblink的一堆信息很麻烦的话,可以在db1中建一个view来解决。
CREATE VIEW remote_people_user_name AS
SELECT * FROM dblink('hostaddr=192.168.0.222 port=5432 dbname=db2 user=postgres password=postgres',
'SELECT user_name From people') AS t(user_name text);
然后就可以从这个view中查询数据了。
SELECT * FROM remote_people_user_name;
www.2cto.com
如果不只是查询数据,而是需要修改db2的数据的情况下怎么弄呢?
1. 先执行dblink_connect保持连接
SELECT dblink_connect('connection','hostaddr=192.168.0.222 port=5432 dbname=db2 user=postgres password=postgres');
2. 执行BEGIN命令
SELECT dblink_exec('connection', 'BEGIN');
3. 执行数据操作(update,insert,create等命令)
SELECT dblink_exec('connection', 'insert 。。。数据操作');
4. 执行事务提交
SELECT dblink_exec('connection', 'COMMIT');
5. 解除连接
SELECT dblink_disconnect('connection');
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇update时连接表的语句 下一篇PostgreSQL一键安装包在XP系统中..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: