使用函数访问python中的postgresql数据库



让我首先说我对Python和Postgresql非常陌生,所以我觉得我有点不知所措。我的最终目标是连接到postgresql中的dvdrental数据库,并能够访问/操作数据。到目前为止,我有:

  1. 创建了一个.config文件夹,其中有一个database.ini和我的登录凭据
  2. 在我的src中,我有一个config.py文件夹,并使用config解析器,如下所示:
def config(filename='.config/database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
  1. 然后在我的src中,我有一个tasks.py文件,它有一个基本的连接函数,请参见下面:
import pandas as pd
from clients.config import config
import psycopg
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg.connect(**params)

# create a cursor
cur = conn.cursor()

# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)

# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')

if __name__ == '__main__':
connect()

现在,它运行并打印出Postgresql数据库版本,一切都很好&很好,但我很难弄清楚如何更改代码,使其更通用,也许只是创建一个光标?

我需要connect函数来基本上只连接到dvdrental数据库并创建一个游标,这样我就可以使用我的连接从数据库中选择其他需要的";任务"——例如,我希望能够创建另一个函数,如下所示:

def select_from_table(cursor, table_name, schema):
cursor.execute(f"SET search_path TO {schema}, public;")
results= cursor.execute(f"SELECT * FROM {table_name};").fetchall()
return results

但我正在为如何创建与dvdrental数据库的连接而苦苦挣扎;一个光标,这样我就可以实际获取数据,并用它创建panda表等等。

所以它会像任务1正在连接到数据库任务2是与数据库交互(选择表等等(任务3是将2的结果转换为pandas-df-

非常感谢你的帮助!!这是我正在上的一门课上的一个项目,我非常不知所措,一直在谷歌上不停地搜索研究,结果似乎毫无进展。

事实上,建立连接是最困难的一步。我知道这可能会让人不知所措,但你走在了正确的轨道上。

只需将connect中的这三行复制到select_from_table方法中

params = config()
conn = psycopg.connect(**params)
cursor = conn.cursor()

它看起来是这样的(最后还添加了conn.close(((:

def select_from_table(cursor, table_name, schema):
params = config()
conn = psycopg.connect(**params)
cursor = conn.cursor()
cursor.execute(f"SET search_path TO {schema}, public;")
results= cursor.execute(f"SELECT * FROM {table_name};").fetchall()
conn.close()
return results

最新更新