用“ with语句”关闭psyopcg2中的连接的正确方法是什么?

时间:2019-03-25 09:26:07

标签: python pandas psycopg2

我想知道,使用with语句和psyopcg2关闭Postgres数据库连接的正确方法是什么。

import pandas as pd
import psycopg2
def create_df_from_postgres(params: dict,
                                   columns: str,
                                   tablename: str,
                                   ) -> pd.DataFrame:

    with psycopg2.connect(**params) as conn:
        data_sql = pd.read_sql_query(
          "SELECT " + columns + ", SUM(total)"
          " AS total FROM " + str(tablename),
          con=conn
          )
    # i need to close conection here:
        # conn.close()

    # or here:
    conn.close()
    return data_sql

这是处理连接的更好方法吗?

def get_ci_method_and_date(params: dict,
                           columns: str,
                           tablename: str,
                           ) -> pd.DataFrame:

    try:
        connection = psycopg2.connect(**params)
        data_sql = pd.read_sql_query('SELECT ' + columns +
                                     ' FROM ' + str(tablename),
                                     con=connection
                                     )
    finally:
        if(connection):
            connection.close()
    return data_sql

From official psycopg docs

警告与文件对象或其他资源不同,使用块退出连接不会关闭连接,而只会关闭与其关联的事务。如果要确保连接在某一点后关闭,则仍应使用try-catch块:

conn = psycopg2.connect(DSN)
try:
    # connection usage
finally:
    conn.close()

2 个答案:

答案 0 :(得分:1)

关闭连接的正确方法:

From official psycopg docs

  

警告与文件对象或其他资源不同,通过退出连接   阻止不会关闭连接,而只会关闭与   它。如果要确保连接在某一点后关闭,则可以   仍应使用try-catch块:

conn = psycopg2.connect(DSN)
try:
    # connection usage
finally:
    conn.close()

答案 1 :(得分:0)

with语句的全部意义在于,资源退出时会自动清除。因此,根本不需要显式调用conn.close()