活动

天翼云最新优惠活动,涵盖免费试用,产品折扣等,助您降本增效!
热门活动
  • 618智算钜惠季 爆款云主机2核4G限时秒杀,88元/年起!
  • 免费体验DeepSeek,上天翼云息壤 NEW 新老用户均可免费体验2500万Tokens,限时两周
  • 云上钜惠 HOT 爆款云主机全场特惠,更有万元锦鲤券等你来领!
  • 算力套餐 HOT 让算力触手可及
  • 天翼云脑AOne NEW 连接、保护、办公,All-in-One!
  • 中小企业服务商合作专区 国家云助力中小企业腾飞,高额上云补贴重磅上线
  • 出海产品促销专区 NEW 爆款云主机低至2折,高性价比,不限新老速来抢购!
  • 天翼云电脑专场 HOT 移动办公新选择,爆款4核8G畅享1年3.5折起,快来抢购!
  • 天翼云奖励推广计划 加入成为云推官,推荐新用户注册下单得现金奖励
免费活动
  • 免费试用中心 HOT 多款云产品免费试用,快来开启云上之旅
  • 天翼云用户体验官 NEW 您的洞察,重塑科技边界

智算服务

打造统一的产品能力,实现算网调度、训练推理、技术架构、资源管理一体化智算服务
智算云(DeepSeek专区)
科研助手
  • 算力商城
  • 应用商城
  • 开发机
  • 并行计算
算力互联调度平台
  • 应用市场
  • 算力市场
  • 算力调度推荐
一站式智算服务平台
  • 模型广场
  • 体验中心
  • 服务接入
智算一体机
  • 智算一体机
大模型
  • DeepSeek-R1-昇腾版(671B)
  • DeepSeek-R1-英伟达版(671B)
  • DeepSeek-V3-昇腾版(671B)
  • DeepSeek-R1-Distill-Llama-70B
  • DeepSeek-R1-Distill-Qwen-32B
  • Qwen2-72B-Instruct
  • StableDiffusion-V2.1
  • TeleChat-12B

应用商城

天翼云精选行业优秀合作伙伴及千余款商品,提供一站式云上应用服务
进入甄选商城进入云市场创新解决方案
办公协同
  • WPS云文档
  • 安全邮箱
  • EMM手机管家
  • 智能商业平台
财务管理
  • 工资条
  • 税务风控云
企业应用
  • 翼信息化运维服务
  • 翼视频云归档解决方案
工业能源
  • 智慧工厂_生产流程管理解决方案
  • 智慧工地
建站工具
  • SSL证书
  • 新域名服务
网络工具
  • 翼云加速
灾备迁移
  • 云管家2.0
  • 翼备份
资源管理
  • 全栈混合云敏捷版(软件)
  • 全栈混合云敏捷版(一体机)
行业应用
  • 翼电子教室
  • 翼智慧显示一体化解决方案

合作伙伴

天翼云携手合作伙伴,共创云上生态,合作共赢
天翼云生态合作中心
  • 天翼云生态合作中心
天翼云渠道合作伙伴
  • 天翼云代理渠道合作伙伴
天翼云服务合作伙伴
  • 天翼云集成商交付能力认证
天翼云应用合作伙伴
  • 天翼云云市场合作伙伴
  • 天翼云甄选商城合作伙伴
天翼云技术合作伙伴
  • 天翼云OpenAPI中心
  • 天翼云EasyCoding平台
天翼云培训认证
  • 天翼云学堂
  • 天翼云市场商学院
天翼云合作计划
  • 云汇计划
天翼云东升计划
  • 适配中心
  • 东升计划
  • 适配互认证

开发者

开发者相关功能入口汇聚
技术社区
  • 专栏文章
  • 互动问答
  • 技术视频
资源与工具
  • OpenAPI中心
开放能力
  • EasyCoding敏捷开发平台
培训与认证
  • 天翼云学堂
  • 天翼云认证
魔乐社区
  • 魔乐社区

支持与服务

为您提供全方位支持与服务,全流程技术保障,助您轻松上云,安全无忧
文档与工具
  • 文档中心
  • 新手上云
  • 自助服务
  • OpenAPI中心
定价
  • 价格计算器
  • 定价策略
基础服务
  • 售前咨询
  • 在线支持
  • 在线支持
  • 工单服务
  • 建议与反馈
  • 用户体验官
  • 服务保障
  • 客户公告
  • 会员中心
增值服务
  • 红心服务
  • 首保服务
  • 客户支持计划
  • 专家技术服务
  • 备案管家

了解天翼云

天翼云秉承央企使命,致力于成为数字经济主力军,投身科技强国伟大事业,为用户提供安全、普惠云服务
品牌介绍
  • 关于天翼云
  • 智算云
  • 天翼云4.0
  • 新闻资讯
  • 天翼云APP
基础设施
  • 全球基础设施
  • 信任中心
最佳实践
  • 精选案例
  • 超级探访
  • 云杂志
  • 分析师和白皮书
  • 天翼云·创新直播间
市场活动
  • 2025智能云生态大会
  • 2024智算云生态大会
  • 2023云生态大会
  • 2022云生态大会
  • 天翼云中国行
天翼云
  • 活动
  • 智算服务
  • 产品
  • 解决方案
  • 应用商城
  • 合作伙伴
  • 开发者
  • 支持与服务
  • 了解天翼云
      • 文档
      • 控制中心
      • 备案
      • 管理中心
      文档中心

      数据仓库服务

      数据仓库服务

        • 产品动态
        • 产品简介
        • 产品定义
        • 产品优势
        • 功能特性
        • 应用场景
        • 术语解释
        • 与其他云服务的关系
        • DWS权限管理
        • 如何访问DWS
        • 使用限制
        • 技术指标
        • 计费说明
        • 资源节点
        • 产品规格
        • 产品价格
        • 计费模式
        • 购买
        • 变更
        • 续订
        • 退订
        • 快速入门
        • 注册天翼云账号
        • 入门前准备
        • 创建集群
        • 连接集群
        • 查看其它资料并清理资源
        • 用户指南
        • 使用简介
        • 准备工作
        • 创建与删除集群
        • 创建专属集群
        • 包年/包月计费操作
        • 删除集群
        • 连接集群
        • 连接集群的方式
        • 获取集群连接地址
        • 使用gsql命令行客户端连接集群
        • 下载客户端
        • 使用Linux gsql客户端连接集群
        • 使用Windows gsql客户端连接集群
        • 使用SSL进行安全的TCP/IP连接
        • 使用Data Studio图形界面客户端连接集群
        • 使用JDBC和ODBC连接集群
        • 使用Python第三方库psycopg2连接集群
        • 使用Python第三方库PyGreSQL连接集群
        • 管理数据库连接
        • 监控与告警
        • Cloud Eye监控集群
        • 事件通知
        • 事件通知概述
        • 查看事件
        • 告警管理
        • 告警管理简介
        • 告警规则
        • 订阅告警通知
        • 变配与扩容
        • 查看巡检
        • 节点管理
        • 节点变更
        • 集群扩容
        • 集群重分布
        • 重分布
        • 查看重分布详情
        • 集群缩容
        • 规格变更
        • 集群高可用
        • 管理快照
        • 快照概述
        • 手动快照
        • 自动快照
        • 查看快照信息
        • 恢复快照
        • 集群容灾
        • 容灾概述
        • 创建容灾
        • 查看容灾信息
        • 容灾管理
        • 容灾互斥案例
        • 集群绑定和解绑ELB
        • 管理CN节点
        • 集群运维
        • 智能运维
        • 智能运维概览
        • 管理运维计划
        • 查看运维任务
        • 解除只读
        • 管理快照
        • 重启集群
        • 重置密码
        • 升级集群
        • 审计日志
        • 审计日志概述
        • 管理控制台审计日志
        • 数据库审计日志
        • 设置数据库审计日志
        • 转储数据库审计日志
        • 查看数据库审计日志
        • 集群管理
        • 修改数据库参数
        • 查看集群状态
        • 查看集群详情
        • 修改集群名称
        • 管理集群访问域名
        • 集群拓扑图
        • 删除集群
        • 管理企业项目
        • 管理创建失败的集群
        • 集群主备恢复
        • 启停集群
        • 数据库用户管理
        • 升级集群
        • 集群日志管理
        • 集群安全管理
        • 设置三权分立
        • 资源管理
        • 概述
        • 资源池
        • 功能介绍
        • 添加资源池
        • 修改资源池
        • 删除资源池
        • 资源管理计划
        • 资源管理计划操作
        • 资源管理计划阶段
        • 空间管理
        • 管理数据源
        • 管理MRS数据源
        • 逻辑集群管理
        • 逻辑集群概述
        • 添加/删除逻辑集群
        • 管理逻辑集群
        • 教程:已有数据的物理集群转换逻辑集群
        • 教程:新物理集群划分为逻辑集群
        • 最佳实践
        • 导入导出
        • 导入数据最佳实践
        • GDS实践指南
        • 教程:从OBS导入数据到集群
        • 教程:使用GDS从远端服务器导入数据
        • 调优表实践
        • 表结构设计
        • 调优表概述
        • 选择表模型
        • 步骤1:创建初始表并加装样例数据
        • 步骤2:测试初始表结构下的系统性能并建立基线
        • 步骤3:调优表操作具体步骤
        • 步骤4:创建新表并加载数据
        • 步骤5:测试新的表结构下的系统性能
        • 步骤6:调优表性能评估
        • 附录:表创建语法
        • 附录使用说明
        • 初始表创建
        • 设计调优后二次表创建
        • 外表创建
        • 数据库管理
        • SQL查询优秀实践
        • 分析正在执行的SQL
        • 数据倾斜查询优秀实践
        • 导入过程存储倾斜即时检测
        • 快速定位查询存储倾斜的表
        • 用户管理优秀实践
        • 查看表和数据库的信息
        • 安全管理
        • 基于角色的权限管理(RBAC)
        • 实现数据列的加解密
        • 常见问题
        • 计费类
        • 购买类
        • 操作类
        • 通用问题
        • 集群管理
        • 数据库连接
        • 数据导入导出
        • 帐户、密码、权限
        • 数据库使用
        • 数据库性能
        • 相关协议
        • 数据仓库服务产品服务协议
        • 文档下载
        • 数据仓库服务用户操作指南
        • 数据仓库服务用户开发指南
        • 数据仓库服务工具指南
        • 数据仓库服务SQL语法参考
        • 数据仓库服务故障排除
        • 数据仓库服务错误码参考
          无相关产品

          本页目录

          帮助中心数据仓库服务用户指南连接集群使用Python第三方库PyGreSQL连接集群
          使用Python第三方库PyGreSQL连接集群
          更新时间 2024-10-10 11:48:45
          • 新浪微博
          • 微信
            扫码分享
          • 复制链接
          最近更新时间: 2024-10-10 11:48:45
          分享文章
          • 新浪微博
          • 微信
            扫码分享
          • 复制链接
          本章节主要介绍如何使用Python第三方库PyGreSQL连接集群。

          用户在创建好数据仓库集群后使用PyGreSQL第三方库连接到集群,则可以使用Python访问DWS ,并进行数据表的各类操作。

          连接集群前的准备

          • DWS 集群已绑定弹性IP。
          • 已获取DWS 集群的数据库管理员用户名和密码。
          注意

          由于MD5算法已经被证实存在碰撞可能,已严禁将之用于密码校验算法。当前DWS 采用默认安全设计,默认禁止MD5算法的密码校验,可能导致开源客户端无法正常连接的问题。建议先检查一下数据库参数password_encryption_type参数是否为1,如果取值不为1,需要修改,修改方法参见《用户指南》的“[修改数据库参数](https://www.ctyun.cn/document/10014061/10047788)”章节;然后修改一次准备使用的数据库用户的密码。

          说明
          当前DWS出于安全考虑,已经默认不再使用MD5存储密码摘要了,这将导致使用开源驱动或者客户端无法正常连接数据库。需要您调整一下密码策略后再创建一个新用户或者对老用户做一次密码修改,方可使用开源协议中使用的MD5认证算法。

          数据库中是不会存储您的密码原文的,而是存储的密码的HASH摘要,在密码校验时与客户端发来的密码摘要进行比对(中间会有加盐操作)。故当您改变了密码算法策略时,数据库也是无法还原您的密码,再生成新的HASH算法的摘要值的。必须您手动修改一次密码或者创建一个新用户,这时新的密码将会采用您设置的HASH算法进行摘要存储,用于下次连接认证。

          • 已获取DWS 集群的公网访问地址,含IP地址和端口。具体请参见 获取集群连接地址。
          • 已安装PyGreSQL第三方库。
          说明
          CentOS、Redhat等操作系统中使用yum命令安装,命令为:yum install PyGreSQL。

          PyGreSQL的使用依赖于PostgreSQL的libpq动态库(32位的PyGreSQL对应32位的libpq,64位的PyGreSQL对应64位的libpq),Linux中可以依赖yum命令解决。在Windows系统使用PyGreSQL需要先安装libpq,主要方式有两种:

          1.安装PostgreSQL,并配置libpq、ssl、crypto动态库位置到环境变量PATH中。

          2.安装psqlodbc,使用PostgreSQL ODBC驱动携带的libpq、ssl、crypto动态库。

          使用约束

          由于PyGreSQL是基于PostgreSQL的客户端接口,它的功能DWS并不能完全支持。具体支持情况请见下表。

          说明
          以下接口支持情况是基于Python 3.8.5及PyGreSQL 5.2.4版本。

          DWS对PyGreSQL主要接口支持情况

          PyGreSQL 支持 备注
          Module functions and constants connect–Open a PostgreSQL connection Y -
          Module functions and constants get_pqlib_version–get the version of libpq Y -
          Module functions and constants get/set_defhost–default server host [DV] Y -
          Module functions and constants get/set_defport–default server port [DV] Y -
          Module functions and constants get/set_defopt–default connection options [DV] Y -
          Module functions and constants get/set_defbase–default database name [DV] Y -
          Module functions and constants get/set_defuser–default database user [DV] Y -
          Module functions and constants get/set_defpasswd–default database password [DV] Y -
          Module functions and constants escape_string–escape a string for use within SQL Y -
          Module functions and constants escape_bytea–escape binary data for use within SQL Y -
          Module functions and constants unescape_bytea–unescape data that has been retrieved as text Y -
          Module functions and constants get/set_namedresult–conversion to named tuples Y -
          Module functions and constants get/set_decimal–decimal type to be used for numeric values Y -
          Module functions and constants get/set_decimal_point–decimal mark used for monetary values Y -
          Module functions and constants get/set_bool–whether boolean values are returned as bool objects Y -
          Module functions and constants get/set_array–whether arrays are returned as list objects Y -
          Module functions and constants get/set_bytea_escaped–whether bytea data is returned escaped Y -
          Module functions and constants get/set_jsondecode–decoding JSON format Y -
          Module functions and constants get/set_cast_hook–fallback typecast function Y -
          Module functions and constants get/set_datestyle–assume a fixed date style Y -
          Module functions and constants get/set_typecast–custom typecasting Y -
          Module functions and constants cast_array/record–fast parsers for arrays and records Y -
          Module functions and constants Type helpers Y -
          Module functions and constants Module constants Y -
          Connection–The connection object query–execute a SQL command string Y -
          Connection–The connection object send_query - executes a SQL command string asynchronously Y -
          Connection–The connection object query_prepared–execute a prepared statement Y -
          Connection–The connection object prepare–create a prepared statement Y -
          Connection–The connection object describe_prepared–describe a prepared statement Y -
          Connection–The connection object reset–reset the connection Y -
          Connection–The connection object poll - completes an asynchronous connection Y -
          Connection–The connection object cancel–abandon processing of current SQL command Y -
          Connection–The connection object close–close the database connection Y -
          Connection–The connection object transaction–get the current transaction state Y -
          Connection–The connection object parameter–get a current server parameter setting Y -
          Connection–The connection object date_format–get the currently used date format Y -
          Connection–The connection object fileno–get the socket used to connect to the database Y -
          Connection–The connection object set_non_blocking - set the non-blocking status of the connection Y -
          Connection–The connection object is_non_blocking - report the blocking status of the connection Y -
          Connection–The connection object getnotify–get the last notify from the server N 数据库不支持listen/notify
          Connection–The connection object inserttable–insert a list into a table Y copy命令中如果有\n,请使用双引号引用此字段
          Connection–The connection object get/set_notice_receiver–custom notice receiver Y -
          Connection–The connection object putline–write a line to the server socket [DA] Y -
          Connection–The connection object getline–get a line from server socket [DA] Y -
          Connection–The connection object endcopy–synchronize client and server [DA] Y -
          Connection–The connection object locreate–create a large object in the database [LO] N 大对象相关操作
          Connection–The connection object getlo–build a large object from given oid [LO] N 大对象相关操作
          Connection–The connection object loimport–import a file to a large object [LO] N 大对象相关操作
          Connection–The connection object Object attributes Y -
          The DB wrapper class Initialization Y -
          The DB wrapper class pkey–return the primary key of a table Y -
          The DB wrapper class get_databases–get list of databases in the system Y -
          The DB wrapper class get_relations–get list of relations in connected database Y -
          The DB wrapper class get_tables–get list of tables in connected database Y -
          The DB wrapper class get_attnames–get the attribute names of a table Y -
          The DB wrapper class has_table_privilege–check table privilege Y -
          The DB wrapper class get/set_parameter–get or set run-time parameters Y -
          The DB wrapper class begin/commit/rollback/savepoint/release–transaction handling Y -
          The DB wrapper class get–get a row from a database table or view Y -
          The DB wrapper class insert–insert a row into a database table Y -
          The DB wrapper class update–update a row in a database table Y -
          The DB wrapper class upsert–insert a row with conflict resolution Y -
          The DB wrapper class query–execute a SQL command string Y -
          The DB wrapper class query_formatted–execute a formatted SQL command string Y -
          The DB wrapper class query_prepared–execute a prepared statement Y -
          The DB wrapper class prepare–create a prepared statement Y -
          The DB wrapper class describe_prepared–describe a prepared statement Y -
          The DB wrapper class delete_prepared–delete a prepared statement Y -
          The DB wrapper class clear–clear row values in memory Y -
          The DB wrapper class delete–delete a row from a database table Y 元组必须有唯一键或者主键
          The DB wrapper class truncate–quickly empty database tables Y -
          The DB wrapper class get_as_list/dict–read a table as a list or dictionary Y -
          The DB wrapper class escape_literal/identifier/string/bytea–escape for SQL Y -
          The DB wrapper class unescape_bytea– unescape data retrieved from the database Y -
          The DB wrapper class encode/decode_json–encode and decode JSON data Y -
          The DB wrapper class use_regtypes–determine use of regular type names Y -
          The DB wrapper class notification_handler–create a notification handler N 数据库不支持listen/notify
          The DB wrapper class Attributes of the DB wrapper class Y -
          Query methods getresult–get query values as list of tuples Y -
          Query methods dictresult/dictiter–get query values as dictionaries Y -
          Query methods namedresult/namediter–get query values as named tuples Y -
          Query methods scalarresult/scalariter–get query values as scalars Y -
          Query methods one/onedict/onenamed/onescalar–get one result of a query Y -
          Query methods single/singledict/singlenamed/singlescalar–get single result of a query Y -
          Query methods listfields–list fields names of previous query result Y -
          Query methods fieldname, fieldnum–field name/number conversion Y -
          Query methods fieldinfo–detailed info about query result fields Y -
          Query methods ntuples–return number of tuples in query object Y -
          Query methods memsize–return number of bytes allocated by query result Y -
          LargeObject–Large Objects open–open a large object N 大对象相关操作
          LargeObject–Large Objects close–close a large object N 大对象相关操作
          LargeObject–Large Objects read, write, tell, seek, unlink–file-like large object handling N 大对象相关操作
          LargeObject–Large Objects size–get the large object size N 大对象相关操作
          LargeObject–Large Objects export–save a large object to a file N 大对象相关操作
          LargeObject–Large Objects Object attributes N 大对象相关操作
          The Notification Handler Instantiating the notification handler N 数据库不支持listen/notify
          The Notification Handler Invoking the notification handler N 数据库不支持listen/notify
          The Notification Handler Sending notifications N 数据库不支持listen/notify
          The Notification Handler Auxiliary methods N 数据库不支持listen/notify
          pgdb
          Module functions and constants connect–Open a PostgreSQL connection Y -
          Module functions and constants get/set/reset_typecast–Control the global typecast functions Y -
          Module functions and constants Module constants Y -
          Module functions and constants Errors raised by this module Y -
          Connection–The connection object close–close the connection Y -
          Connection–The connection object commit–commit the connection Y -
          Connection–The connection object rollback–roll back the connection Y -
          Connection–The connection object cursor–return a new cursor object Y -
          Connection–The connection object Attributes that are not part of the standard Y -
          Cursor–The cursor object description–details regarding the result columns Y -
          Cursor–The cursor object rowcount–number of rows of the result Y -
          Cursor–The cursor object close–close the cursor Y -
          Cursor–The cursor object execute–execute a database operation Y -
          Cursor–The cursor object executemany–execute many similar database operations Y -
          Cursor–The cursor object callproc–Call a stored procedure Y -
          Cursor–The cursor object fetchone–fetch next row of the query result Y -
          Cursor–The cursor object fetchmany–fetch next set of rows of the query result Y -
          Cursor–The cursor object fetchall–fetch all rows of the query result Y -
          Cursor–The cursor object arraysize - the number of rows to fetch at a time Y -
          Cursor–The cursor object Methods and attributes that are not part of the standard Y -
          Type–Type objects and constructors Type constructors Y -
          Type–Type objects and constructors Type objects Y -

          在Linux环境使用PyGreSQL第三方库连接集群

          1.以root用户登录Linux环境。

          2.执行以下命令创建python_dws.py文件。

          vi python_dws.py
          

          请复制粘贴以下内容放入python_dws.py文件中:

          #!/usr/bin/env python3 
          # _*_ encoding:utf-8 _*_ 
            
          from __future__ import print_function 
            
          import pg 
            
            
          def create_table(connection): 
              print("Begin to create table") 
              try: 
                  connection.query("drop table if exists test;" 
                                   "create table test(id int, name text);") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("Table created successfully") 
            
            
          def insert_data(connection): 
              print("Begin to insert data") 
              try: 
                  connection.query("insert into test values(1,'number1');") 
                  connection.query("insert into test values(2,'number2');") 
                  connection.query("insert into test values(3,'number3');") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("Insert data successfully") 
            
            
          def update_data(connection): 
              print("Begin to update data") 
              try: 
                  result = connection.query("update test set name = 'numberupdated' where id=1;") 
                  print("Total number of rows updated :", result) 
                  result = connection.query("select * from test order by 1;") 
                  rows = result.getresult() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1], "\n") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("After Update, Operation done successfully") 
            
            
          def delete_data(connection): 
              print("Begin to delete data") 
              try: 
                  result = connection.query("delete from test where id=3;") 
                  print("Total number of rows deleted :", result) 
                  result = connection.query("select * from test order by 1;") 
                  rows = result.getresult() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1], "\n") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("After Delete,Operation done successfully") 
            
            
          def select_data(connection): 
              print("Begin to select data") 
              try: 
                  result = connection.query("select * from test order by 1;") 
                  rows = result.getresult() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1]) 
              except pg.InternalError as e: 
                  print(e) 
                  print("select failed") 
              else: 
                  print("Operation done successfully") 
            
            
          if __name__ == '__main__': 
              try: 
                  conn = pg.DB(host='10.154.70.231', 
                               port=8000, 
                               dbname='gaussdb', # 需要连接的database 
                               user='dbadmin', 
                               passwd='password')  # 数据库用户密码 
              except pg.InternalError as ex: 
                  print(ex) 
                  print("Connect database failed") 
              else: 
                  print("Opened database successfully") 
                  create_table(conn) 
                  insert_data(conn) 
                  select_data(conn) 
                  update_data(conn) 
                  delete_data(conn) 
                  conn.close()
          

          或使用dbapi接口实现:

          #!/usr/bin/python 
          # -*- coding: UTF-8 -*- 
            
          from __future__ import print_function 
            
          import pg 
          import pgdb 
            
            
          def create_table(connection): 
              print("Begin to create table") 
              try: 
                  cursor = connection.cursor() 
                  cursor.execute("drop table if exists test;" 
                                 "create table test(id int, name text);") 
                  connection.commit() 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("Table created successfully") 
                  cursor.close() 
            
            
          def insert_data(connection): 
              print("Begin to insert data") 
              try: 
                  cursor = connection.cursor() 
                  cursor.execute("insert into test values(1,'number1');") 
                  cursor.execute("insert into test values(2,'number2');") 
                  cursor.execute("insert into test values(3,'number3');") 
                  connection.commit() 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("Insert data successfully") 
                  cursor.close() 
            
            
          def update_data(connection): 
              print("Begin to update data") 
              try: 
                  cursor = connection.cursor() 
                  cursor.execute("update test set name = 'numberupdated' where id=1;") 
                  connection.commit() 
                  print("Total number of rows updated :", cursor.rowcount) 
                  cursor.execute("select * from test;") 
                  rows = cursor.fetchall() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1], "\n") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("After Update, Operation done successfully") 
            
            
          def delete_data(connection): 
              print("Begin to delete data") 
              try: 
                  cursor = connection.cursor() 
                  cursor.execute("delete from test where id=3;") 
                  connection.commit() 
                  print("Total number of rows deleted :", cursor.rowcount) 
                  cursor.execute("select * from test;") 
                  rows = cursor.fetchall() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1], "\n") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("After Delete,Operation done successfully") 
            
            
          def select_data(connection): 
              print("Begin to select data") 
              try: 
                  cursor = connection.cursor() 
                  cursor.execute("select * from test;") 
                  rows = cursor.fetchall() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1], "\n") 
              except pg.InternalError as e: 
                  print(e) 
                  print("select failed") 
              else: 
                  print("Operation done successfully") 
                  cursor.close() 
            
            
          if __name__ == '__main__': 
              try: 
                  conn = pgdb.connect(host='10.154.70.231', 
                                                port='8000', 
                                                database='gaussdb', # 需要连接的database 
                                                user='dbadmin', 
                                                password='password') # 数据库用户密码 
              except pg.InternalError as ex: 
                  print(ex) 
                  print("Connect database failed") 
              else: 
                  print("Opened database successfully") 
                  create_table(conn) 
                  insert_data(conn) 
                  select_data(conn) 
                  update_data(conn) 
                  delete_data(conn) 
                  conn.close()
          

          3.按照实际集群信息,修改python_dws.py文件中的集群公网访问地址、集群端口号、数据库名称、数据库用户名、数据库密码。

          说明

          PyGreSQL接口不提供重试连接的能力,您需要在业务代码中实现重试处理。

          conn = pgdb.connect(host='10.154.70.231', 
                                                port='8000', 
                                                database='gaussdb', # 需要连接的database 
                                                user='dbadmin', 
                                                password='password') # 数据库用户密码
          

          4.执行以下命令,使用PyGreSQL第三方库连接集群。

          python python_dws.py
          

          在Windows环境使用PyGreSQL第三方库连接集群

          1.在Windows系统中,单击“开始”按钮 ,在搜索框中,键入 cmd ,然后在结果列表中单击“cmd.exe”打开命令提示符窗口。

          2.在命令提示符窗口中,执行以下命令创建python_dws.py文件。

          type nul> python_dws.py
          

          请复制粘贴以下内容放入python_dws.py文件中:

          #!/usr/bin/env python3 
          # _*_ encoding:utf-8 _*_ 
            
          from __future__ import print_function 
            
          import pg 
            
            
          def create_table(connection): 
              print("Begin to create table") 
              try: 
                  connection.query("drop table if exists test;" 
                                   "create table test(id int, name text);") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("Table created successfully") 
            
            
          def insert_data(connection): 
              print("Begin to insert data") 
              try: 
                  connection.query("insert into test values(1,'number1');") 
                  connection.query("insert into test values(2,'number2');") 
                  connection.query("insert into test values(3,'number3');") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("Insert data successfully") 
            
            
          def update_data(connection): 
              print("Begin to update data") 
              try: 
                  result = connection.query("update test set name = 'numberupdated' where id=1;") 
                  print("Total number of rows updated :", result) 
                  result = connection.query("select * from test order by 1;") 
                  rows = result.getresult() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1], "\n") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("After Update, Operation done successfully") 
            
            
          def delete_data(connection): 
              print("Begin to delete data") 
              try: 
                  result = connection.query("delete from test where id=3;") 
                  print("Total number of rows deleted :", result) 
                  result = connection.query("select * from test order by 1;") 
                  rows = result.getresult() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1], "\n") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("After Delete,Operation done successfully") 
            
            
          def select_data(connection): 
              print("Begin to select data") 
              try: 
                  result = connection.query("select * from test order by 1;") 
                  rows = result.getresult() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1]) 
              except pg.InternalError as e: 
                  print(e) 
                  print("select failed") 
              else: 
                  print("Operation done successfully") 
            
            
          if __name__ == '__main__': 
              try: 
                  conn = pg.DB(host='10.154.70.231', 
                               port=8000, 
                               dbname='gaussdb', # 需要连接的database 
                               user='dbadmin', 
                               passwd='password')  # 数据库用户密码 
              except pg.InternalError as ex: 
                  print(ex) 
                  print("Connect database failed") 
              else: 
                  print("Opened database successfully") 
                  create_table(conn) 
                  insert_data(conn) 
                  select_data(conn) 
                  update_data(conn) 
                  delete_data(conn) 
                  conn.close()
          

          或使用dbapi接口实现::

          #!/usr/bin/python 
          # -*- coding: UTF-8 -*- 
            
          from __future__ import print_function 
            
          import pg 
          import pgdb 
            
            
          def create_table(connection): 
              print("Begin to create table") 
              try: 
                  cursor = connection.cursor() 
                  cursor.execute("drop table if exists test;" 
                                 "create table test(id int, name text);") 
                  connection.commit() 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("Table created successfully") 
                  cursor.close() 
            
            
          def insert_data(connection): 
              print("Begin to insert data") 
              try: 
                  cursor = connection.cursor() 
                  cursor.execute("insert into test values(1,'number1');") 
                  cursor.execute("insert into test values(2,'number2');") 
                  cursor.execute("insert into test values(3,'number3');") 
                  connection.commit() 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("Insert data successfully") 
                  cursor.close() 
            
            
          def update_data(connection): 
              print("Begin to update data") 
              try: 
                  cursor = connection.cursor() 
                  cursor.execute("update test set name = 'numberupdated' where id=1;") 
                  connection.commit() 
                  print("Total number of rows updated :", cursor.rowcount) 
                  cursor.execute("select * from test;") 
                  rows = cursor.fetchall() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1], "\n") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("After Update, Operation done successfully") 
            
            
          def delete_data(connection): 
              print("Begin to delete data") 
              try: 
                  cursor = connection.cursor() 
                  cursor.execute("delete from test where id=3;") 
                  connection.commit() 
                  print("Total number of rows deleted :", cursor.rowcount) 
                  cursor.execute("select * from test;") 
                  rows = cursor.fetchall() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1], "\n") 
              except pg.InternalError as e: 
                  print(e) 
              else: 
                  print("After Delete,Operation done successfully") 
            
            
          def select_data(connection): 
              print("Begin to select data") 
              try: 
                  cursor = connection.cursor() 
                  cursor.execute("select * from test;") 
                  rows = cursor.fetchall() 
                  for row in rows: 
                      print("id = ", row[0]) 
                      print("name = ", row[1], "\n") 
              except pg.InternalError as e: 
                  print(e) 
                  print("select failed") 
              else: 
                  print("Operation done successfully") 
                  cursor.close() 
            
            
          if __name__ == '__main__': 
              try: 
                  conn = pgdb.connect(host='10.154.70.231', 
                                                port='8000', 
                                                database='gaussdb', # 需要连接的database 
                                                user='dbadmin', 
                                                password='password') # 数据库用户密码 
              except pg.InternalError as ex: 
                  print(ex) 
                  print("Connect database failed") 
              else: 
                  print("Opened database successfully") 
                  create_table(conn) 
                  insert_data(conn) 
                  select_data(conn) 
                  update_data(conn) 
                  delete_data(conn) 
                  conn.close()
          

          3.按照实际集群信息,修改python_dws.py文件中的集群公网访问地址、集群端口号、数据库名称、数据库用户名、数据库密码。

          PyGreSQL接口不提供重试连接的能力,您需要在业务代码中实现重试处理。

          conn = pgdb.connect(host='10.154.70.231', 
                                                port='8000', 
                                                database='gaussdb', # 需要连接的database 
                                                user='dbadmin', 
                                                password='password') # 数据库用户密码
          

          4.执行以下命令,使用PyGreSQL第三方库连接集群。

          python python_dws.py
          
          文档反馈

          建议您登录后反馈,可在建议与反馈里查看问题处理进度

          鼠标选中文档,精准反馈问题

          选中存在疑惑的内容,即可快速反馈问题,我们会跟进处理

          知道了

          上一篇 :  使用Python第三方库psycopg2连接集群
          下一篇 :  管理数据库连接
          搜索 关闭
          ©2025 天翼云科技有限公司版权所有 增值电信业务经营许可证A2.B1.B2-20090001
          公司地址:北京市东城区青龙胡同甲1号、3号2幢2层205-32室
          备案 京公网安备11010802043424号 京ICP备 2021034386号
          ©2025天翼云科技有限公司版权所有
          京ICP备 2021034386号
          备案 京公网安备11010802043424号
          增值电信业务经营许可证A2.B1.B2-20090001
          用户协议 隐私政策 法律声明