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');

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...