有时候的业务须要参照其余数据库的数据。sql
咱们能够在程序中分别从两个数据库中取值而后处理。但这样开发效率和性能都不是很好。数据库
若是两个数据库都是PostgreSQL的话,用扩展的DBLINK功能很是简单。post
好比一个数据db1,db2。首先须要把db1加入dblink扩展。性能
示例1:取得db2的用户表的用户名spa
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;
1. 先执行dblink_connect保持链接.net
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等命令)code
SELECT dblink_exec('connection', 'insert 。。。数据操做');
4. 执行事务提交blog
SELECT dblink_exec('connection', 'COMMIT');
5. 解除链接事务
SELECT dblink_disconnect('connection');