python3创建连接池连接polardb-o(postgre)数据库

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: 风过无言花易落
# @Date  : 2022/07/04 22:30
# @Desc  : polardb-o (底层连接 postgres 数据库) 数据库连接池操作

import psycopg2.extras
from DBUtils.PooledDB import PooledDB
import threading

class PsycopgConn:
    _instance_lock = threading.Lock()

    def __init__(self,host, port, user, password, database):
        """
        初始化连接池
        :return:
        """
        try:
            pool = PooledDB(
                creator=psycopg2,  # 使用连接数据库的模块 psycopg2
                maxconnections=10,  # 连接池允许的最大连接数,0 和 None 表示不限制连接数
                mincached=1,  # 初始化时,链接池中至少创建的空闲的链接,0 表示不创建
                maxcached=8,  # 链接池中最多闲置的链接,0 和 None 不限制
                blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
                maxusage=None,  # 一个链接最多被重复使用的次数,None 表示无限制
                setsession=[],  # 开始会话前执行的命令列表
                host=host,
                port=port,
                user=user,
                password=password,
                database=database)
            self._pool = pool
        except:
            print('connect postgresql error')
            self.close_pool()

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            with PsycopgConn._instance_lock:
                if not hasattr(cls, '_instance'):
                    PsycopgConn._instance = object.__new__(cls)
                return PsycopgConn._instance

    def get_pool_conn(self):
        """
        获取连接池连接
        :return:
        """
        if not self._pool:
            self.init_pool()
        return self._pool.connection()

    def close_pool(self):
        """
        关闭连接池连接
        :return:
        """
        if self._pool != None:
            self._pool.close()

    def fetch_one(self, sql):
        """
        查询
        :param sql:
        :return:
        """
        try:
            conn = self.get_pool_conn()
            # cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)  # 设置返回格式为字典
            cursor = conn.cursor()
            cursor.execute(sql)
            result = cursor.fetchone()
        except Exception as e:
            print('execute sql {0} is error:{1}'.format(sql,e))
        finally:
            cursor.close()
            conn.close()
        return result

    def fetch_all(self, sql):
        """
        查询
        :param sql:
        :return:
        """
        try:
            conn = self.get_pool_conn()
            # cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)  # 设置返回格式为字典
            cursor = conn.cursor()
            cursor.execute(sql)
            result = cursor.fetchall()
        except Exception as e:
            print('execute sql {0} is error:{1}'.format(sql,e))
        finally:
            cursor.close()
            conn.close()
        return result

    def InsertSql(self, sql):
        """
        插入数据
        :param sql:
        :return:
        """
        try:
            conn = self.get_pool_conn()
            cursor = conn.cursor()
            cursor.execute(sql)
            result = True
        except Exception as e:
            print('execute sql {0} is error:{1}'.format(sql,e))
        finally:
            cursor.close()
            conn.commit()
            conn.close()
        return result

    def execute_sql(self, sql):
        """
        更新数据
        :param sql:
        :return:
        """
        try:
            conn = self.get_pool_conn()
            cursor = conn.cursor()
            cursor.execute(sql)
            result = True
        except Exception as e:
            print('execute sql {0} is error:{1}'.format(sql,e))
        finally:
            cursor.close()
            conn.commit()
            conn.close()
        return result
if __name__ == "__main__":
    a= PsycopgConn('10.10.10.255',12345,'dbname','dbpwd','database')
    b = a.fetch_one('select 1 ')
    print(b)
    a.close_pool()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值