首页 > 解决方案 > DataFrame.to_sql 相当于在 psycopg2 中使用“返回 id”?

问题描述

使用插入数据时,我可以使用RETURNING PostgreSQL语句psycopg2检索id插入的行:

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]

这很好,因为我需要它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
)

但是没有直接的方法来检索id实际插入此记录时创建的 PostgreSQL。

是否有一个不错且可靠的解决方法来获得它?
或者我应该坚持使用 psycopg2 来使用 SQL 查询编写我的大字典?

标签: pythonpandaspostgresqldataframe

解决方案


推荐阅读