python - 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 查询编写我的大字典?
解决方案
推荐阅读
- uwp - 如何在 ListView 上调用 itemClick?
- node.js - 从另一个字段移动数据时,Mongoose Mongodb Cast to Embedded / Number 值失败
- c# - 当前上下文中不存在名称 Process.Start
- r - 犰狳矩阵列的非连续访问
- ios - 从 firebase 检索数据并设置 VC 以匹配用户偏好
- node.js - 为什么在 IBM Cloud 上托管的 Cloud Foundry 应用程序中删除了 fs(文件系统)?
- sql - Oracle SELF JOIN 提出建议
- python - 在python中为groupby()选择单个值
- css - iOS 13 及更低版本 CSS 动画闪烁
- android - 如何使 Webview 在 Kiosk 自助服务中工作