Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
On this page

Show all

Psycopg Package

Updated on 2024-08-20 GMT+08:00
  1. Prepare related drivers and dependent libraries. Obtain the package GaussDB-Kernel_Database version number_OS version number_64bit_Python.tar.gz from the release package.

    After the decompression, the following folders are generated:

    • psycopg2: psycopg2 library file
    • lib: lib library file

  1. Load the driver.

    • Before using the driver, perform the following operations:
      1. Decompress the driver package of the corresponding version.
        tar zxvf xxxx-Python.tar.gz
      2. Copy psycopg2 to the site-packages folder in the Python installation directory as the root user.
        su root
        cp psycopg2 $(python3 -c 'import site; print(site.getsitepackages()[0])') -r
      3. Change the psycopg2 directory permission to 755.
        chmod 755 $(python3 -c 'import site; print(site.getsitepackages()[0])')/psycopg2 -R
      4. Add the psycopg2 directory to the environment variable $PYTHONPATH and validate it.
        export PYTHONPATH=$(python3 -c 'import site; print(site.getsitepackages()[0])'):$PYTHONPATH
      5. For non-database users, configure the lib directory in LD_LIBRARY_PATH after decompression.
        export LD_LIBRARY_PATH=path/to/lib:$LD_LIBRARY_PATH
    • Load a database driver before creating a database connection.
      1
      import  psycopg2
      

  2. Connect to a database.

    Connect to the database in non-SSL mode.

    1. Use the psycopg2.connect function to obtain the connection object.
    2. Use the connection object to create a cursor object.

    Connect to the database in SSL mode.

    When you use psycopy2 to connect to the GaussDB server, you can enable SSL to encrypt the communication between the client and server. To enable SSL, you must have the server certificate, client certificate, and private key files. For details on how to obtain these files, see related documents and commands of OpenSSL.

    1. Use the .ini file (the configparser package of Python can parse this type of configuration file) to save the configuration information about the database connection.
    2. Add SSL connection parameters sslmode, sslcert, sslkey, and sslrootcert to the connection options.
      1. sslmode: For details about the options, see Table 1.
      2. sslcert: client certificate path.
      3. sslkey: client key path.
      4. sslrootcert: root certificate path.
    3. Use the psycopg2.connect function to obtain the connection object.
    4. Use the connection object to create a cursor object.
      CAUTION:

      To use SSL to connect to the database, ensure that the Python interpreter is compiled in the mode of generating a dynamic link library (.so) file. You can perform the following steps to check the connection mode of the Python interpreter:

      1. Run the import ssl command in the Python interpreter to import SSL.
      2. Run the ps ux command to query the PID of the Python interpreter. Assume that the PID is ******.
      3. In the shell CLI, run the pmap -p ****** | grep ssl command and check whether the command output contains the path related to libssl.so. If yes, the Python interpreter is compiled in dynamic link mode.
    Table 1 sslmode options

    sslmode

    Enable SSL Encryption

    Description

    disable

    No

    SSL connection is not enabled.

    allow

    Possible

    If the database server requires SSL connection, SSL connection can be enabled. However, authenticity of the database server will not be verified.

    prefer

    Possible

    If the database supports SSL connection, SSL connection is preferred. However, authenticity of the database server will not be verified.

    require

    Yes

    SSL connection is required, but only data is encrypted. However, authenticity of the database server will not be verified.

    verify-ca

    Yes

    SSL connection is required, and the validity of the server CA must be verified.

    verify-full

    Yes

    The SSL connection must be enabled, which is not supported by GaussDB currently.

  3. Run SQL statements.

    1. Construct an operation statement and use %s as a placeholder. During execution, psycopg2 will replace the placeholder with the parameter value. You can add the RETURNING clause to obtain the automatically generated column values.
    2. Use the cursor.execute method to execute one row of SQL statement, and use the cursor.executemany method to execute multiple rows of SQL statements.

  4. Process the result set.

    1. cursor.fetchone(): fetches the next row in a query result set and returns a sequence. If no data is available, null is returned.
    2. cursor.fetchall(): fetches all remaining rows in a query result and returns a list. An empty list is returned when no rows are available.
    NOTE:

    For database-specific data types, such as tinyint, the corresponding columns in the query result are character strings.

  5. Disable the connection.

    After you complete required data operations in a database, close the database connection. Call the close method such as connection.close() to close the connection.

    CAUTION:

    This method closes the database connection and does not automatically call commit(). If you just close the database connection without calling commit() first, changes will be lost.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback