安装psycopg2
pip install psycopg2-binary
创建 PostgreSQL 的工具类postgre_connection.py
import psycopg2
# 打开数据库
def open_db(host, user, password, dbname):
return psycopg2.connect("host=" + host + " dbname=" + dbname + " user=" + user + " password=" + password)
# 获取游标
def get_cursor(db):
return db.cursor()
# 执行 SQL 语句
def sql_commit(db, cursor, sql, param=None):
try:
# 执行sql语句
cursor.execute(sql, param)
# 提交到数据库执行
db.commit()
# 获取所有记录列表
results = cursor.fetchall()
return results
except Exception as e:
print(e)
# 如果发生错误则回滚
db.rollback()
return None
finally:
cursor.close()
db.close()
使用该工具类
from db.postgre_connection import open_db, get_cursor, sql_commit
if __name__ == "__main__":
try:
db = open_db('host', 'user', 'password', 'database')
cursor = get_cursor(db)
sql = "select * from users"
user_list = sql_commit(db, cursor, sql)
return user_list
except Exception:
print("数据库连接失败")
return None
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)