Python WITH AS连接postgresql示例

一、技术说明

用python connect Postgresql是程序开发中经常遇到的需求,但是,连接数据库需要考虑创建(Create)和关闭(Close)的连接与游标的问题。为此,我们采用python编程模式中的年with as数据结构,实现数据库的创建与自动关闭。

本示例涉及如下技术点:

二、编码示例

1. 创建数据库连接配置文件:pg_config.ini

[postgresql]
host = 127.0.0.1
database = mydb
user = steven
password = 11111111
port = 5432

2.数据库连接对象:PostgresqlConnect

'''
PostgresConnect
-------------
POSTGRESQL数据库连接服务,根据数据库连接信息(主机IP、端口号、数据库名称、用户名、密码 或者 数据库连接配置文件ini),创建数据库连接
Author: steven
Date : 2024-3-21
版本: v1.0.0
'''

import configparser as cp
import curses
import sys
from contextlib import contextmanager

import psycopg2 as pg2


class PostgresqlConnect:
    """this is to initialize the object of postgresqlconnect, configfile and section are one group and
    others are another group for inputting parameters."""

    def __init__(
            self,
            configfile: str | None = None,
            section: str = 'postgresql',
            *,
            host: str | None = None,
            port: str | None = None,
            database: str | None = None,
            user: str | None = None,
            password: str | None = None,
    ):
        self.params = {}
        if configfile is not None:
            parser = cp.ConfigParser()
            parser.read(configfile)
            if parser.has_section(section):
                self.params = dict(parser.items(section))
            else:
                raise Exception('Section {0} not found in the {1} file'.format(
                    section, configfile))
        else:
            self.params['host'] = host
            self.params['port'] = port
            self.params['database'] = database
            self.params['user'] = user
            self.params['password'] = password
        # print('The database\'s configuration is:', self.params)

    """this is to create a connnection to database when entered and 
    close it when left"""
    @contextmanager
    def connected(self):
        print('Connecting to:', self.params)
        conn = pg2.connect(**self.params)
        # create a cursor
        cur = conn.cursor()
        try:
            yield cur
        finally:
            cur.close()
            conn.close()
            print('Database connection is closed')

3.测试验证代码:main

# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

def print_hi(name, python_learing=None):

    from postgresql_connection.postgresql_connection import PostgresqlConnect as pc
    pc_mydb = pc('postgresql_connection/pg_config.ini')

    with pc_mydb.connected() as cur:
        # execute a statement
        print('PostgreSQL database version:')
        cur.execute('SELECT version()')

        # display the PostgreSQL database server version
        db_version = cur.fetchone()
        print(db_version)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值