python psycopg2 連接pg 建立連接池


# -*- coding: utf-8 -*-
from psycopg2.pool import ThreadedConnectionPool,SimpleConnectionPool,PersistentConnectionPool

from constant import pg_name, pg_user, pg_pw, pg_host, pg_port
from public import gen_sql

# pgpool = ThreadedConnectionPool(1, 5, dbname=pg_name, user=pg_user, host=pg_host, password=pg_pw, port=pg_port)

# pgpool = SimpleConnectionPool(1, 5, dbname=pg_name, user=pg_user, host=pg_host, password=pg_pw, port=pg_port)
pgpool = PersistentConnectionPool(1, 100, dbname=pg_name, user=pg_user, host=pg_host, password=pg_pw, port=pg_port)

# 不管是哪種方式建立的連接池, 多進程或者多線程都會導致數據cursor 關閉, 出錯等數據庫問題, 即使是在每個進程中都建立連接池也不行(我的測試結果, 水平有限)

def conn_exe(*sp):
  conn = pgpool.getconn()  # 獲取連接
  cursor = conn.cursor()  # 獲取cursor
  cursor.execute(*sp)
  conn.commit()  # 沒次操作都要提交
  pgpool.putconn(conn)  # 放回連接, 防止其他程序pg無連接可用
  return cursor


def fetchone_sql(*sp):
  cursor = conn_exe(*sp)
  # desc = cursor.description  # cursor 的具體描述信息
  fetchone = cursor.fetchone()
  cursor.close()
  return fetchone


def fetchall_sql(*sp):

  cursor = conn_exe(*sp)
  fetchall = cursor.fetchall()
  cursor.close()
  return fetchall


def get_insert_id(*sp): 

  *sp += " returning id"   # 插入語句這樣返回 插入的id(或者其他字段 看上一行的SQL 語句) 

  cursor = conn_exe(*sp)
  insert_id = cursor.fetchone()[0]
  cursor.close()
  return insert_id


def run_sql(*sp): 

  cursor = conn_exe(*sp)
  cursor.close()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM