s.k*_*s.k 5 python postgresql dataframe pandas
使用插入数据时,psycopg2我可以使用RETURNING PostgreSQLid语句检索插入的行:
import psycopg2
conn = my_connection_parameters()
curs = conn.cursor()
sql_insert_data_query = (
"""INSERT INTO public.data
(created_by, comment)
VALUES ( %(user)s, %(comment)s )
RETURNING id; # the id is automatically managed by the database.
"""
)
curs.execute(
sql_insert_data_query,
{
"user": 'me',
"comment": 'my comment'
}
)
conn.commit()
data_id = curs.fetchone()[0]
Run Code Online (Sandbox Code Playgroud)
这很好,因为我需要它id来写入其他数据,例如关联表。
但是当有一个大字典要写入 PostgreSQL 时(键是列标识符),依赖 pandas 的DataFrame.to_sql()方法会更方便:
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://', creator=my_connection_parameters)
df = pd.DataFrame(my_dict, index=[0]) # this is a "one-row" DataFrame, each column being created from the dict keys
df.to_sql(
name='user_table',
con=engine,
schema='public',
if_exists='append',
index=False
)
Run Code Online (Sandbox Code Playgroud)
但是没有直接的方法来检索id实际插入该记录时 PostgreSQL 创建的记录。
有没有一个好的、可靠的解决方法来获取它?
或者我应该坚持使用 psycopg2 使用 SQL 查询编写我的大字典?