您的位置:首页 > 数据库

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

2017-10-11 18:05 429 查看
转自:http://blog.csdn.net/hantiannan/article/details/7553108

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

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

如果两个数据库都是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中查询数据了。

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’);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库 postgresql