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的数据的情况下怎么弄呢?
有时候的业务需要参照其他数据库的数据。
我们可以在程序中分别从两个数据库中取值然后处理。但这样开发效率和性能都不是很好。
如果两个数据库都是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’);相关文章推荐
- Postgres访问其他PostgresQL数据库的功能DBLINK
- Postgres访问其他PostgresQL数据库的功能DBLINK
- Postgres访问其他PostgresQL数据库的功能DBLINK
- 在oracle中建立dblink访问其他数据库
- PostgreSQL数据库开启IP访问功能
- PostgreSQL数据库dblink和postgres_fdw扩展使用比较
- 在oracle中建立dblink访问其他数据库
- 不同数据库间的数据访问--dblink
- Golang 访问PostgreSQL数据库增删改查
- php怎么将数据库封装,然后提供数据接口让其他API什么的访问
- 如何让其他计算机访问我的计算机上数据库mysql?
- oracle通过透明网关(Oracle Transparent Geteways),访问ms sql server和其他数据库
- 【转发】oracle 使用dblink访问postgresql数据库
- 如何访问其他apk的数据库
- postgres无法访问数据库
- sqlserver2008r2数据库使用触发器对sa及其他数据库账号访问进行IP限制
- PostgreSQL与其他数据库的比较
- .NET 访问PostgreSQL数据库
- 基于.NET平台的Windows编程实战(八)— 数据库管理及其他辅助功能的实现
- PostgreSql 数据库的访问权限配置