PostgreSQL Python
| Введение | |
| Импорт из .csv | |
| Простейший пример | |
| Более реальный пример | |
| Похожие статьи |
Введение
Введение
Рассмотрим простой пример подключения к базе данных с помощью
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 from configparser import ConfigParser def config(filename="database.ini", section="postgresql"): # create a parser parser = ConfigParser() # read config file parser.read(filename) # 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.
| SQLite3 Python | |
| Реальный пример | |
| Ошибки | |
| Python | |
| Базы данных |