PostgreSQL Python

Содержание
Введение
Простое подключение с psycopg2
Удаление БД
Похожие статьи

Введение

В этой статье вы можете изучить примеры работы с PostgreSQL на языке программирования Python

Простое подключение с psycopg2

Рассмотрим простой пример подключения к базе данных с помощью psycopg2

Учётные данные будем хранить в файле database.ini читать из него будем скриптом config.py на основе configparser а само подлючение реализуем в pg_demo.py

pg_demo/ |-- .gitignore |-- config.py |-- database.ini `-- pg_demo.py

# .gitignore database.ini __pycache__

[postgresql] host=localhost database=postgres user=postgres password=secret

#!/usr/bin/python # config.py import os from configparser import ConfigParser def config(filename="database.ini", section="postgresql"): # create a parser parser = ConfigParser() file_path = os.path.join(os.path.dirname(__file__), filename) # read config file parser.read(file_path) # get section, default to postgresql db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception(f"Section {section} not found in the {filename} file") return db

#!/usr/bin/python import psycopg2 from config import config def connect(): """ Connect to the PostgreSQL database server """ conn = None try: # read connection parameters params = config() # connect to the PostgreSQL server print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) # create a cursor cur = conn.cursor() # execute a statement print('PostgreSQL database version:') cur.execute('SELECT version()') # display the PostgreSQL database server version db_version = cur.fetchone() print(db_version) # close the communication with the PostgreSQL cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() print('Database connection closed.') if __name__ == '__main__': connect()

python pg_demo.py

Connecting to the PostgreSQL database... PostgreSQL database version: ('PostgreSQL 12.8, compiled by Visual C++ build 1914, 64-bit',) Database connection closed.

Удаление БД

Для удаления базы данных используем сетап из предыдущего примера.

Подключаться будем с помощью config.py

Обычно удобно использовать

conn.autocommit = True

Также обратите внимание на то, что имя базы данных заключено в двойные кавычки. Это сделано на случай, если в нём будут дефисы.

import psycopg2 import config def drop_db(db_name: str): print(f"drop_db({db_name})") params = config.credentials() print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) cur = conn.cursor() conn.autocommit = True try: cur.execute(f'DROP DATABASE IF EXISTS "{db_name}"') except (Exception, psycopg2.DatabaseError) as e: print(e) finally: cur.close() conn.close() if __name__ == '__main__': drop_db("obsoleted_db")

Article author: Andrei Olegovich

Похожие статьи
SQLite3 Python
Реальный пример
Ошибки
Python
Базы данных

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: