python操作PostgreSQL数据库


import psycopg2 as pg2

# 返回数据库PostgreSQL连接
def get_db_conn():
    # 创建连接
    return pg2.connect(database='test', user='admin', password='admin', host='127.0.0.1', port='10001')


# 操作数据库PostgreSQL,返回一条结果
def db_fetchone(sql):
    try:
        conn = get_db_conn()
        cur = conn.cursor()
        cur.execute(sql)
        rows = cur.fetchone()  # 返回一条结果,返回多条结果使用rows = cur.fetchall()

        return rows[0]
    except pg2.DatabaseError as e:
        print('Error $s' % e)

    finally:
        conn.commit()
        cur.close()
        conn.close()

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM