DEV Community

leo
leo

Posted on

Connect to openGauss database (Python)

Python
Psycopg is a Python API for executing SQL statements. It can provide a unified access interface for PostgreSQL and openGauss databases, and applications can perform data operations based on it. Psycopg2 encapsulates libpq, and some codes are implemented in C language, which is efficient and safe. It has client-side and server-side cursors, asynchronous communication and notifications, and supports "COPY TO/COPY FROM" functions. Supports multiple types of Python out of the box, and adapts to PostgreSQL data types; through a flexible object adaptation system, it can be extended and customized. Psycopg2 is Unicode and Python 3 compatible.

The openGauss database provides support for Psycopg2 features, and supports psycopg2 connections through SSL mode.

Table 1 Psycopg supported platforms

operating system

platform

EulerOS 2.5

x86_64 bit

EulerOS 2.8

ARM64 bit

load driver
Before using the driver, you need to do the following:

Download the compiled psycopg2 compressed package from the openGauss official website.

Note: The version of psycopg2 downloaded from the openGauss official website is adapted to Python3.6. If you use other versions of Python, you need to compile psycopg2 yourself. The compilation method is basically the same as that under the PostgreSQL database. Just need to modify the code of the setup.py version number verification part during compilation, which can be realized by the following command:

sed -i "s/(pgmajor, pgminor, pgpatch)/(9, 2, 4)/g" setup.py
Unzip the driver package corresponding to the version, and copy psycopg2 to the third-party package folder (namely the site-packages directory) of the python installation directory.

Make sure that the permission of the psycopg2 directory is at least 755, so as not to prompt that the file cannot be accessed due to permission issues when calling.

For non-database users, you need to configure the decompressed lib directory in the LD_LIBRARY_PATH environment variable.

Before creating a database connection, the following database drivers need to be loaded:

import psycopg2
Connect to the database
The following Python code shows how to connect to an existing database. If the database does not exist, it will be created automatically, and finally a database object will be returned.

!/usr/bin/python

import psycopg2
conn = psycopg2.connect(database="testdb", user="openGauss", password="xxxxxxxx", host="127.0.0.1", port="26000")
In the above code, please replace the bold font according to the specific situation. Specify here to use testdb as the database name.

Top comments (0)