微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Postgres访问其他PostgresQL数据库的功能DBLINK

有时候的业务需要参照其他数据库的数据。

我们可以在程序中分别从两个数据库中取值然后处理。但这样开发效率和性能都不是很好。

如果两个数据库都是Postgresql的话,用扩展的DBLINK功能非常简单。

比如一个数据db1,db2。首先需要把db1加入dblink扩展。

示例1:取得db2的用户表的用户名


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中查询数据了。
  1. SELECT * FROM remote_people_user_name;

如果不只是查询数据,而是需要修改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');

原文地址:https://www.jb51.cc/postgresql/196428.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐