postgresql dblink 使用

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

猜你喜欢

转载自906179271.iteye.com/blog/2267875