postgresql dblink 使用

[size=small]dblink的使用 pg的跨库查询工具
select dblink_connect('host=localhost port=5432 user=sqluser dbname=tm_samples password=****');
select dblink_disconnect();

1、安装
在安装包的目录下
[postgres@localhost postgresql-9.1.1]$ find /postgresql-9.1.1/ -name dblink
/postgresql-9.1.1/contrib/dblink

使用postgres用户安装即可
[postgres@localhost dblink]$ make && make install

在实际安装目录的lib下多了一个dblink.so
/pg/lib/postgresql
-rwxr-xr-x 1 postgres postgres 49174 Jul 22 23:22 dblink.so

进入psql,创建扩展dblink
postgres=# \c liodb lio
You are now connected to database "liodb" as user "lio".
liodb=# create extension dblink;
CREATE EXTENSION

也可以使用命令:psql -f dblink.sql -d 数据库 -U 用户名

2、使用
select dblink_connect('hostaddr=192.168.10.173 port=5432 dbname=tina user=postgres password=tina');
--这个函数用来建立到远程数据库的连接。

liodb=# select dblink_connect('hostaddr=192.168.10.173 port=5432 dbname=tina user=postgres password=tina');
dblink_connect
----------------
OK
(1 row)

liodb=# select * from father; ---这个表在lio中是不存在的
ERROR: relation "father" does not exist at character 15
STATEMENT: select * from father;
ERROR: relation "father" does not exist
LINE 1: select * from father;

#重点在于as 后的重命名表,需要定义表结构,表中的类型需要和select返回的类型保持一致。 ^
liodb=# select * from dblink('select name from father') as t_1(name text);
name
-----------
Las vegas
Mariposa
madison
(3 rows)

这样就可以查询到tina库中的father表的内容

--向远程数据库插入一条记录
select dblink_exec('insert into father values(/'moxige/',/'3.54/',/'899/')');

查询:select * from dblink('select * from father')as fa(name text,population float,altutude text);

3、操作完成,断开连接
select dblink_diconnect();[/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值