PostgreSQL 客户端安装配置与连接演示

科技   2024-11-14 07:50   北京  
作者 | JiekeXu
来源 |公众号 JiekeXu DBA之路(ID: JiekeXu_IT)
如需转载请联系授权 | (个人微信 ID:JiekeXu_DBA)
大家好,我是 JiekeXu,江湖人称“强哥”,荣获 Oracle ACE Pro 称号,墨天轮 MVP,墨天轮年度“墨力之星”,拥有 Oracle OCP/OCM 认证,MySQL 5.7/8.0 OCP 认证以及 PCA、PCTA、OBCA、OGCA、KCP 等众多国产数据库认证证书,今天和大家一起来看看PostgreSQL 客户端安装配置与连接演示,欢迎点击最上方蓝字“JiekeXu DBA之路”关注我的微信公众号,然后点击右上方三个点“设为星标”置顶,更多干货文章才能第一时间推送,谢谢!

前  言

上周五快要下班的时候,接到一个需求帮助,问怎么在内网环境的 Linux 上离线安装 PostgreSQL 客户端访问另一套 PG 主备库。原客户的问题比较模糊,转述给我的也就是这样的需求,不知道是需要类似 psql 还是类似 pgadmin 可图形化的工具,这里惯性思维认为 Linux 下就应该是非图形化命令行界面,那么也就按照这个思路往下走了。

正  文

PostgreSQL 是一个发展了 20 多年的强大的开源关系型数据库,它支持多种客户端工具,这些工具可以帮助我们更方便地连接、管理和操作 PostgreSQL 数据库。以下是常用的 PostgreSQL 客户端工具:

PG 常用客户端工具


psql 命令行工具

我们都知道当安装完 PostgreSQL 之后,我们便可以通过 psql 客户端工具登录到数据库实例,比如增删改查,创建数据库等一些数据库管理操作。但是如果需要远程通过 A 主机访问 B 主机上的数据库实例,那么 A 主机则必须要有客户端才可访问,所以则需要安装上面提到的任一客户端工具。

由于前面的需求是 Linux 主机,无图形界面的话,首先想到的则是 psql 客户端工具,但由于 PG 官方目前好像没有提供单独的 psql 安装包,我们则可以选择编译安装二进制服务包来达到目的,说干就干。

  • 下载软件包

  1. https://www.postgresql.org/ftp/source/

  2. --我们选择 2023 年发布的 pg14.9,注意不用太新,否则 OS 不支持编译安装报错

  3. postgresql-14.9.tar.gz

  • 创建 postgre 用户

  1. groupadd postgres

  2. useradd -g postgres postgres

  3. echo "postgres" |passwd --stdin postgres

  4. 密码:postgres

  • yum 源安装 rpm 包

  1. --测试 yum

  2. yum repolist


  3. yum -y install coreutils glib2 lrzsz mpstat dstatsysstat e4fsprogs xfsprogs ntp readline-devel zlib-devel openssl-develpam-devel libxml2-devel libxslt-devel python-devel tcl-devel gcc makesmartmontools flex bison perl-devel perl-Ext Utils* openldap-devel jadetex openjade bzip2

  • 解压软件包

  1. su - postgres

  2. mkdir pgdata

  3. tar xvf /var/lib/pgsql/postgresql-14.9.tar.bz2 -C /var/lib/pgsql

  • 编译

  1. cd postgresql-14.9/

  2. ./configure --prefix=/var/lib/pgsql/pgdata --with-perl --with-python


  3. --看到如下代码则 configure 完成

  4. checking Python.h usability... yes

  5. checking Python.h presence... yes

  6. checking for Python.h... yes

  7. checking for xmllint... /bin/xmllint

  8. checking for xsltproc... /bin/xsltproc

  9. checking for fop... no

  10. checking for dbtoepub... no

  11. checking whether gcc -std=gnu99 supports -Wl,--as-needed... yes

  12. configure: using compiler=gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)

  13. configure: using CFLAGS=-Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2

  14. configure: using CPPFLAGS= -D_GNU_SOURCE

  15. configure: using LDFLAGS= -Wl,--as-needed

  16. configure: creating ./config.status

  17. config.status: creating GNUmakefile

  18. config.status: creating src/Makefile.global

  19. config.status: creating src/include/pg_config.h

  20. config.status: creating src/include/pg_config_ext.h

  21. config.status: creating src/interfaces/ecpg/include/ecpg_config.h

  22. config.status: linking src/backend/port/tas/dummy.s to src/backend/port/tas.s

  23. config.status: linking src/backend/port/posix_sema.c to src/backend/port/pg_sema.c

  24. config.status: linking src/backend/port/sysv_shmem.c to src/backend/port/pg_shmem.c

  25. config.status: linking src/include/port/linux.h to src/include/pg_config_os.h

  26. config.status: linking src/makefiles/Makefile.linux to src/Makefile.port

接着执行 gmake world 完成编译

  1. -bash-4.2$ gmake world

  2. gmake -C ./src/backend generated-headers

  3. gmake[1]: Entering directory `/var/lib/pgsql/postgresql-14.9/src/backend'

  4. gmake -C catalog distprep generated-header-symlinks

  5. gmake[2]: Entering directory `/var/lib/pgsql/postgresql-14.9/src/backend/catalog'

  6. gmake[2]: Nothing to be done for `distprep'.

  7. prereqdir=`cd './' >/dev/null && pwd` && \


  8. --看到有如下代码则表示编译完成

  9. gmake[2]: Leaving directory `/var/lib/pgsql/postgresql-14.9/contrib/jsonb_plperl'

  10. gmake -C hstore_plpython all

  11. gmake[2]: Entering directory `/var/lib/pgsql/postgresql-14.9/contrib/hstore_plpython'

  12. gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I/usr/include/python2.7 -DPLPYTHON_LIBNAME='"plpython2"' -I../../src/pl/plpython -I../../contrib -I. -I. -I../../src/include -D_GNU_SOURCE -c -o hstore_plpython.o hstore_plpython.c

  13. gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -shared -o hstore_plpython2.so hstore_plpython.o -L../../src/port -L../../src/common -Wl,--as-needed -Wl,-rpath,'/usr/lib64',--enable-new-dtags -L/usr/lib64 -lpython2.7 -lpthread -ldl -lutil -lm

  14. gmake[2]: Leaving directory `/var/lib/pgsql/postgresql-14.9/contrib/hstore_plpython'

  15. gmake -C jsonb_plpython all

  16. gmake[2]: Entering directory `/var/lib/pgsql/postgresql-14.9/contrib/jsonb_plpython'

  17. gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I../../src/pl/plpython -I/usr/include/python2.7 -DPLPYTHON_LIBNAME='"plpython2"' -I. -I. -I../../src/include -D_GNU_SOURCE -c -o jsonb_plpython.o jsonb_plpython.c

  18. gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -shared -o jsonb_plpython2.so jsonb_plpython.o -L../../src/port -L../../src/common -Wl,--as-needed -Wl,-rpath,'/usr/lib64',--enable-new-dtags -L/usr/lib64 -lpython2.7 -lpthread -ldl -lutil -lm

  19. gmake[2]: Leaving directory `/var/lib/pgsql/postgresql-14.9/contrib/jsonb_plpython'

  20. gmake -C ltree_plpython all

  21. gmake[2]: Entering directory `/var/lib/pgsql/postgresql-14.9/contrib/ltree_plpython'

  22. gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -I/usr/include/python2.7 -DPLPYTHON_LIBNAME='"plpython2"' -I../../src/pl/plpython -I../../contrib -I. -I. -I../../src/include -D_GNU_SOURCE -c -o ltree_plpython.o ltree_plpython.c

  23. gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -fPIC -shared -o ltree_plpython2.so ltree_plpython.o -L../../src/port -L../../src/common -Wl,--as-needed -Wl,-rpath,'/usr/lib64',--enable-new-dtags -L/usr/lib64 -lpython2.7 -lpthread -ldl -lutil -lm

  24. gmake[2]: Leaving directory `/var/lib/pgsql/postgresql-14.9/contrib/ltree_plpython'

  25. gmake[1]: Leaving directory `/var/lib/pgsql/postgresql-14.9/contrib'

可以选择编译安装包含扩展包和文档

  1. gmake install-world //包含扩展包和文档


  2. --看到有 extension 关键字有如下代码则表示编译完成

  3. /bin/install -c -m 644 ./hstore_plpythonu.control ./hstore_plpython2u.control ./hstore_plpython3u.control '/var/lib/pgsql/pgdata/share/extension/'

  4. /bin/install -c -m 644 ./hstore_plpythonu--1.0.sql ./hstore_plpython2u--1.0.sql ./hstore_plpython3u--1.0.sql '/var/lib/pgsql/pgdata/share/extension/'

  5. gmake[2]: Leaving directory `/var/lib/pgsql/postgresql-14.9/contrib/hstore_plpython'

  6. gmake -C jsonb_plpython install

  7. gmake[2]: Entering directory `/var/lib/pgsql/postgresql-14.9/contrib/jsonb_plpython'

  8. /bin/mkdir -p '/var/lib/pgsql/pgdata/lib'

  9. /bin/mkdir -p '/var/lib/pgsql/pgdata/share/extension'

  10. /bin/mkdir -p '/var/lib/pgsql/pgdata/share/extension'

  11. /bin/install -c -m 755 jsonb_plpython2.so '/var/lib/pgsql/pgdata/lib/jsonb_plpython2.so'

  12. /bin/install -c -m 644 ./jsonb_plpythonu.control ./jsonb_plpython2u.control ./jsonb_plpython3u.control '/var/lib/pgsql/pgdata/share/extension/'

  13. /bin/install -c -m 644 ./jsonb_plpythonu--1.0.sql ./jsonb_plpython2u--1.0.sql ./jsonb_plpython3u--1.0.sql '/var/lib/pgsql/pgdata/share/extension/'

  14. gmake[2]: Leaving directory `/var/lib/pgsql/postgresql-14.9/contrib/jsonb_plpython'

  15. gmake -C ltree_plpython install

  16. gmake[2]: Entering directory `/var/lib/pgsql/postgresql-14.9/contrib/ltree_plpython'

  17. /bin/mkdir -p '/var/lib/pgsql/pgdata/lib'

  18. /bin/mkdir -p '/var/lib/pgsql/pgdata/share/extension'

  19. /bin/mkdir -p '/var/lib/pgsql/pgdata/share/extension'

  20. /bin/install -c -m 755 ltree_plpython2.so '/var/lib/pgsql/pgdata/lib/ltree_plpython2.so'

  21. /bin/install -c -m 644 ./ltree_plpythonu.control ./ltree_plpython2u.control ./ltree_plpython3u.control '/var/lib/pgsql/pgdata/share/extension/'

  22. /bin/install -c -m 644 ./ltree_plpythonu--1.0.sql ./ltree_plpython2u--1.0.sql ./ltree_plpython3u--1.0.sql '/var/lib/pgsql/pgdata/share/extension/'

  23. gmake[2]: Leaving directory `/var/lib/pgsql/postgresql-14.9/contrib/ltree_plpython'

  24. gmake[1]: Leaving directory `/var/lib/pgsql/postgresql-14.9/contrib'

编译完成后,则会在 pgdata 的 bin 目录下面生成我们需要的可执行文件,如下所示,包含 psql 在内的很多 PG 工具的可执行文件,我们可通过这里的 psql 可执行程序登录到远程的 PG 实例。

  1. -bash-4.2$ ll

  2. total 16

  3. drwxr-xr-x 2 postgres postgres 4096 Nov 2 01:35 bin

  4. drwxr-xr-x 6 postgres postgres 4096 Nov 2 01:35 include

  5. drwxr-xr-x 4 postgres postgres 4096 Nov 2 01:35 lib

  6. drwxr-xr-x 8 postgres postgres 4096 Nov 2 01:35 share

  7. -bash-4.2$ pwd

  8. /var/lib/pgsql/pgdata

  9. -bash-4.2$ cd bin

  10. -bash-4.2$ ll psql

  11. -rwxr-xr-x 1 postgres postgres 656808 Nov 2 01:35 psql

  12. -bash-4.2$ ls

  13. clusterdb ecpg pg_basebackup pg_ctl pg_recvlogical pg_test_timing postmaster

  14. createdb initdb pgbench pg_dump pg_resetwal pg_upgrade psql

  15. createuser oid2name pg_checksums pg_dumpall pg_restore pg_verifybackup reindexdb

  16. dropdb pg_amcheck pg_config pg_isready pg_rewind pg_waldump vacuumdb

  17. dropuser pg_archivecleanup pg_controldata pg_receivewal pg_test_fsync postgres vacuumlo

如下所示,通过远程 psql 登录访问则和本机操作无二,我们通过 14.9 的客户端访问了我远程 13.12 的数据库实例,值得注意的是,远程实例需要在 pg_ha.conf 开放访问权限,以及相应的用户也需要有连接权限才可以。

  1. [postgres@jiekexu1 data]$ cat pg_hba.conf| grep -A2 IPv4

  2. # an integer (between 0 and 32 (IPv4) or 128 (IPv6) inclusive) that

  3. # specifies the number of significant bits in the mask. A host name

  4. # that starts with a dot (.) matches a suffix of the actual host name.

  5. --

  6. # IPv4 local connections:

  7. host all all 127.0.0.1/32 scram-sha-256

  8. host all all 192.168.75.0/24 trust

  9. [postgres@jiekexu1 data]$ pwd

  10. /var/lib/pgsql/13/data

pgAdmin 工具

pgAdmin也是我们常用的PG客户端工具,在 Win10 环境下,这个工具用起来实在是特别的顺手,但要是这个需求放在 Linux 环境下,安装使用 pgAdmin 4 还是很困难的。当我通过可上网的环境下载 rpm 包安装 pgadmin4 是报错 404 网页找不到,不太懂这是不是我的问题(我这里使用的 X64 的 centos7.6,OS 可能会自带 PostgreSQL9.2.24,另外 yum 源使用的是阿里云源 mirrors.aliyun.com,希望有看到的大佬解惑),那么这条路走不通了,我们换条路吧。

  1. rpm -i https://ftp.postgresql.org/pub/pgadmin/pgadmin4/yum/pgadmin4-redhat-repo-2-1.noarch.rpm

  2. yum install pgadmin4

  3. pgadmin4 35 B/s | 146 B 00:04

  4. Errors during downloading metadata for repository 'pgAdmin4':

  5. - Status code: 404 for https://ftp.postgresql.org/pub/pgadmin/pgadmin4/yum/redhat/redhat-8-x86_64/repodata/repomd.xml (IP: 72.32.157.246)

  6. Error: Failed to download metadata for repo 'pgAdmin4': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried

  1. https://www.pgadmin.org/download/pgadmin-4-python/

DBeaver 图形化工具

DBeaver 是一个多数据库管理工具,支持 Windows、macOS 和 Linux 平台,开源免费,界面简洁,支持 SQL 编辑、数据浏览、模式设计等等,所以通过官方网站下载到安装包 dbeaver-ce-24.2.3-stable.x86_64.rpm

  1. https://dbeaver.io/download/


  2. rpm -ivh dbeaver-ce-24.2.3-stable.x86_64.rpm

如果第一次使用,需要开启图形化界面,且可联网下载驱动。

  1. [root@JiekeXu pg]# dbeaver

  2. > Start Eclipse Jobs Mechanism [org.eclipse.core.jobs 3.15.400.v20240619-0602]

  3. > Start Equinox Java Authentication and Authorization Service (JAAS) [org.eclipse.equinox.security 1.4.400.v20240702-1702]

  4. > Start DBeaver Application Standalone [org.jkiss.dbeaver.ui.app.standalone 24.2.3.202410221007]

  5. > Start Eclipse IDE UI Application [org.eclipse.ui.ide.application 1.5.500.v20240711-0817]

  6. 2024-11-11 23:55:16.950 - Error parsing command line: Unrecognized option: --launcher.additionalVmargs

  7. > Start Eclipse IDE UI [org.eclipse.ui.ide 3.22.300.v20240828-1234]

  8. > Start DBeaver Model Registry [org.jkiss.dbeaver.registry 1.0.135.202410221007]

  9. > Start jna [com.sun.jna 5.14.0.v20231211-1200]

  10. > Start DBeaver UI [org.jkiss.dbeaver.ui 5.1.156.202410221007]

  11. > Start Expression Language [org.eclipse.core.expressions 3.9.400.v20240413-1529]

  12. > Start DBeaver Usage Statistics [org.jkiss.dbeaver.ui.statistics 1.0.37.202410221007]

  13. > Start DBeaver Desktop Application Core [org.jkiss.dbeaver.core 24.2.3.202410221007]

  14. 2024-11-11 23:55:17.118 - Initialize desktop platform...

  15. 2024-11-11 23:55:17.212 - BounceCastle bundle found. Use JCE provider BC

  16. > Start Core File Systems [org.eclipse.core.filesystem 1.11.0.v20240824-0952]

  17. > Start Core Resource Management [org.eclipse.core.resources 3.21.0.v20240805-1607]

  18. > Start Team Support Core [org.eclipse.team.core 3.10.500.v20240621-0541]

  19. > Start DBeaver UI Navigator [org.jkiss.dbeaver.ui.navigator 1.0.141.202410221007]

  20. 2024-11-11 23:55:17.380 - Initialize base platform...

  21. > Start DBeaver UI Editors - Base [org.jkiss.dbeaver.ui.editors.base 1.0.141.202410221007]

  22. 2024-11-11 23:55:17.410 - Platform initialized (292ms)

  23. 2024-11-11 23:55:17.416 - DBeaver 24.2.3.202410221007 is starting

  24. 2024-11-11 23:55:17.417 - OS: Linux 3.10.0-957.el7.x86_64 (amd64)

  25. 2024-11-11 23:55:17.417 - Java version: 17.0.6 by Eclipse Adoptium (64bit)

  26. 2024-11-11 23:55:17.417 - Install path: '/usr/share/dbeaver-ce'

  27. 2024-11-11 23:55:17.417 - Instance path: 'file:/root/.local/share/DBeaverData/workspace6/'

  28. 2024-11-11 23:55:17.418 - Memory available 64Mb/1024Mb

  29. 2024-11-11 23:55:17.435 - Create display

  30. 2024-11-11 23:55:17.855 - Starting instance server at http://localhost:30939

  31. 2024-11-11 23:55:17.862 - Run workbench

  32. > Start Eclipse e4 Workbench SWT [org.eclipse.e4.ui.workbench.swt 0.17.500.v20240807-0911]

  33. > Start Eclipse Application Services [org.eclipse.e4.core.services 2.4.400.v20240413-1529]

  34. > Start Eclipse UI Application Services [org.eclipse.e4.ui.services 1.6.300.v20231201-1637]

  35. > Start Eclipse e4 Progress View [org.eclipse.e4.ui.progress 0.4.600.v20240606-1020]

  36. > Start Eclipse Bindings Support [org.eclipse.e4.ui.bindings 0.14.400.v20240321-1245]

  37. > Start Eclipse e4 core commands [org.eclipse.e4.core.commands 1.1.400.v20240424-0444]

  38. > Start EMF XML/XMI Persistence [org.eclipse.emf.ecore.xmi 2.38.0.v20240721-0634]

  39. > Start Eclipse CSS SWT Theme Support [org.eclipse.e4.ui.css.swt.theme 0.14.400.v20240424-0956]

  40. > Start Eclipse e4 Workbench Add-ons [org.eclipse.e4.ui.workbench.addons.swt 1.5.500.v20240620-1945]

  41. > Start Eclipse e4 Workbench SWT Renderer [org.eclipse.e4.ui.workbench.renderers.swt 0.16.500.v20240727-1037]

  42. > Start Eclipse Dependency Injection Extensions [org.eclipse.e4.core.di.extensions 0.18.300.v20240413-1529]

  43. > Start Eclipse CSS SWT Support [org.eclipse.e4.ui.css.swt 0.15.400.v20240321-1245]

  44. > Start Default Text Editor [org.eclipse.ui.editors 3.18.0.v20240807-0735]

  45. > Start Text Editor Framework [org.eclipse.ui.workbench.texteditor 3.18.0.v20240819-1419]

  46. 2024-11-11 23:55:20.136 - Configure workbench window

  47. > Start DBeaver SQL Model [org.jkiss.dbeaver.model.sql 1.0.131.202410221007]

  48. 2024-11-11 23:55:20.301 - Total database drivers: 119 (119)

  49. > Start Help System Core [org.eclipse.help 3.10.400.v20240415-0528]

  50. 2024-11-11 23:55:20.361 - Create actions

  51. 2024-11-11 23:55:20.374 - Disable Eclipse action set 'org.eclipse.ui.edit.text.actionSet.annotationNavigation'

  52. 2024-11-11 23:55:20.375 - Disable Eclipse action set 'org.eclipse.ui.WorkingSetActionSet'

  53. 2024-11-11 23:55:20.376 - Disable Eclipse action set 'org.eclipse.ui.actionSet.openFiles'

  54. 2024-11-11 23:55:20.376 - Create workbench actions

  55. 2024-11-11 23:55:20.867 - Initialize workbench window

  56. 2024-11-11 23:55:20.868 - Error parsing command line: Unrecognized option: --launcher.additionalVmargs

  57. 2024-11-11 23:55:20.873 - Finish initialization

  58. > Start Internet Connection Management UI [org.eclipse.ui.net 1.5.400.v20240413-1529]

  59. > Start Internet Connection Management [org.eclipse.core.net 1.5.500.v20240625-1706]

  60. > Start DBeaver UI Editors - Data [org.jkiss.dbeaver.ui.editors.data 1.0.141.202410221007]

  61. > Start DBeaver UI Editors - SQL [org.jkiss.dbeaver.ui.editors.sql 1.0.141.202410221007]

  62. > Start DBeaver Sample Database [org.jkiss.dbeaver.ext.sample.database 1.0.178.202410221007]

  63. > Start DBeaver Tip of the day [org.jkiss.dbeaver.ext.ui.tipoftheday 1.0.147.202410221007]

  64. > Start GEF Classic Draw2d [org.eclipse.draw2d 3.17.0.202409021815]

  65. > Start GEF Classic GEF (MVC) [org.eclipse.gef 3.19.0.202409021815]

  66. > Start DBeaver ERD UI [org.jkiss.dbeaver.erd.ui 3.0.101.202410221007]

  67. > Start DBeaver ERD Model [org.jkiss.dbeaver.erd.model 1.0.101.202410221007]

  68. > Start DBeaver Dashboard UI [org.jkiss.dbeaver.ui.dashboard 1.0.138.202410221007]


  69. (DBeaver:8107): Gtk-CRITICAL **: 23:55:23.634: gtk_box_gadget_distribute: assertion 'size >= 0' failed in GtkScrollbar

Python 连接 PG

Psycopg 是 Python 编程语言中最流行的 PostgreSQL 适配器,其核心是 Python DB API 2.0 规范的完整实现。一些扩展允许访问 PostgreSQL 提供的许多功能。

  1. https://www.psycopg.org/

  2. https://www.postgresql.org/download/products/2-drivers-and-interfaces/

Psycopg 现在有两个大版本,Psycopg2 和 Psycopg3,Psycopg2 还有两种类型的包(psycopg2 和 psycopg2-binary),其中 psycopg2-binary 相当于绿色版,不需要编译,是为了初学者用 Python 快速和 PostgreSQL 进行连接而用的,对于生产环境,建议编译安装使用psycopg2。Psycopg 是 Python 编程语言的 PostgreSQL 适配器。它是一个 libpq 的包装器,这是官方的 PostgreSQL 客户端库。

安装 psycopg2 的三个先决条件:

  • 从 3.8 到 3.13 的 Python 版本

  • PostgreSQL 服务器版本从 7.4 到 17

  • PostgreSQL 客户端库版本从 9.1 开始

因 Linux7 系统自带 Python2,通过 yum install python3 只是 python3.6.8 版本.

  1. yum install perl-Env zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make libffi-devel python3 -y

  2. yum -y install coreutils glib2 lrzsz mpstat dstatsysstat e4fsprogs xfsprogs ntp readline-devel zlib-devel openssl-develpam-devel libxml2-devel libxslt-devel python3-devel tcl-devel gcc makesmartmontools flex bison perl-devel perl-Ext Utils* openldap-devel jadetex openjade bzip2


  3. yum install libpq-dev*


  4. pip3 install -U pip

  5. pip3 install psycopg2-binary

psycopg2 需要 C、python3-devel、libpq-dev* 依赖包。

In order to perform a local installation you need some prerequisites:

  • a C compiler,

  • Python development headers (e.g. the python3-dev package).

  • PostgreSQL client development headers (e.g. the libpq-dev package).

  • The pg_config program available in the PATH.

  1. [root@JiekeXu pg]# pip3 install psycopg2-binary

  2. WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.

  3. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.

  4. To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.

  5. Collecting psycopg2-binary

  6. Using cached psycopg2-binary-2.9.8.tar.gz (383 kB)

  7. Preparing metadata (setup.py) ... done

  8. Using legacy 'setup.py install' for psycopg2-binary, since package 'wheel' is not installed.

  9. Installing collected packages: psycopg2-binary

  10. Running setup.py install for psycopg2-binary ... done

  11. Successfully installed psycopg2-binary-2.9.8


  12. ## py 导入包 psycopg2

  13. [root@JiekeXu pg]# python3

  14. Python 3.6.8 (default, Oct 5 2022, 16:22:51)

  15. [GCC 8.5.0 20210514 (Red Hat 8.5.0-15.0.1)] on linux

  16. Type "help", "copyright", "credits" or "license" for more information.

  17. >>>

  18. >>> import psycopg2

  19. >>> conn = psycopg2.connect(host="192.168.75.11", port="54321", database="postgres", user="postgres", password="postgres")

  20. >>> cur = conn.cursor()

  21. >>> cur.execute("select now()")

  22. >>> print(cur.fetchone()[0])

  23. 2024-11-13 00:22:25.910934+08:00

  24. >>>

我们也可以直接编写一个 python 脚本,然后运行测试连接。

  1. [root@JiekeXu pg]# vim py_connect_pg.py

  2. import psycopg2

  3. conn = psycopg2.connect(host="192.168.75.11", port="54321", database="postgres", user="postgres", password="postgres")

  4. # 建立游标用来执行数据库操作

  5. cur = conn.cursor()

  6. # 执行一些 SQL 命令,如下仅是演示

  7. cur.execute("select inet_server_addr(),pg_is_in_recovery(),current_database(),current_user")


  8. # 获取 SELECT 返回的元组

  9. rows = cur.fetchall()

  10. for row in rows:

  11. print('inet_server_addr: ' + str(row[0]))

  12. print('pg_is_in_recovery: ' + str(row[1]))

  13. print('current_database: ' + row[2])

  14. print('current_user: ' + row[3])


  15. cur.close()

  16. conn.close()


  17. [root@JiekeXu pg]# python3 py_connect_pg.py

  18. inet_server_addr: 192.168.75.11

  19. pg_is_in_recovery: False

  20. current_database: postgres

  21. current_user: postgres

JDBC 连接串示例

  1. 示例一:

  2. String url = "jdbc:postgresql://localhost/test";

  3. Properties props = new Properties();

  4. props.setProperty("user", "fred");

  5. props.setProperty("password", "secret");

  6. props.setProperty("ssl", "true");

  7. Connection conn = DriverManager.getConnection(url, props);


  8. 示例二:

  9. String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";

  10. Connection conn = DriverManager.getConnection(url);


  11. 示例三:

  12. Properties props = new Properties();

  13. props.setProperty("options", "-c search_path=test,public,pg_catalog -c statement_timeout=90000");

  14. Connection conn = DriverManager.getConnection(url, props);


  15. String url = "jdbc:postgresql://localhost:5432/postgres?options=-c%20search_path=test,public,pg_catalog%20-c%20statement_timeout=90000";

  16. Connection conn = DriverManager.getConnection(url);

总  结

选择合适的 PostgreSQL 客户端工具取决于你的具体需求,包括操作系统、使用习惯、功能需求和预算等因素。对于初学者和日常使用,推荐使用 psql 和 pgAdmin,它们分别提供了强大的命令行和图形界面支持。对于开发人员,DBeaver 和 DataGrip 是不错的选择,因为它们提供了丰富的开发辅助功能。

参考链接

  1. https://www.postgresql.org/ftp/source/

  2. https://www.pgadmin.org/download/

  3. https://www.pgadmin.org/download/pgadmin-4-rpm/

  4. https://dbeaver.io/download/

  5. https://jdbc.postgresql.org/documentation/use/

  6. https://www.psycopg.org/docs/install.html

  7. https://www.postgresql.org/download/products/2-drivers-and-interfaces/

全文完,希望可以帮到正在阅读的你,如果觉得有帮助,可以分享给你身边的朋友,同事,你关心谁就分享给谁,一起学习共同进步~~~



分享几个数据库备份脚本

一文搞懂 Oracle 统计信息

我的 Oracle ACE 心路历程

MOP 系列|MOP 三种主流数据库索引简介

Oracle 主流版本不同架构下的静默安装指南

关机重启导致 ASM 磁盘丢失数据库无法启动

Oracle SQL 性能分析(SPA)原理与实战演练

Oracle 11g 升级到 19c 需要关注的几个问题

Windows 10 环境下 MySQL 8.0.33 安装指南

SQL 大全(四)|数据库迁移升级时常用 SQL 语句

OGG|使用 OGG19c 迁移 Oracle11g 到 19C(第二版)

Oracle 大数据量导出工具——sqluldr2 的安装与使用

Oracle ACE 视角下的国产数据库现状与选型及应对策略

从国产数据库调研报告中你都能了解哪些信息及我的总结建议

使用数据泵利用 rowid 分片导出导入 lob 大表及最佳实践

在归档模式下直接 rm dbf 数据文件并重启数据库还有救吗?

欢迎关注我的公众号【JiekeXu DBA之路】,一起学习新知识!
——————————————————————————
公众号:JiekeXu DBA之路
墨天轮:https://www.modb.pro/u/4347

CSDN :https://blog.csdn.net/JiekeXu
ITPUB:https://blog.itpub.net/69968215
腾讯云:https://cloud.tencent.com/developer/user/5645107——————————————————————————


JiekeXu DBA之路
JiekeXu:Oracle ACE-Pro,获 Oracle OCP/OCM 及 MySQL OCP 认证,墨天轮 MVP,利用闲时间记录菜鸟 DBA 学习成长之路,所发布文字属于个人观点和学习笔记,如有错误及不当之处,敬请批评指正!
 最新文章