SQLAlchemy - 唯一记录插入
我有一个可用的 API,它具有将记录插入数据库的功能。问题是,它在顶部插入任何记录,而不检查重复项/记录是否已存在。
进行该堵塞的最高效的方法是什么?
我正在使用 SQLAlchemy,因为这是我公司的标准(尤其是我们在 gcp 上工作),但我对该库不太熟悉,并且搜索我找不到任何有用的东西。
我当前的代码是:
def db_push(insert: dict)->dict:
def insert_results(results):
rows = []
for i in results:
rows.append(
{
"name": i["Name"],
"id": i["id"],
"amount": I["amount"],
"invoice" : I["invoice"],
"country" : i["Country"]
}
)
return rows
insert = insert_results(insert)
conn = engine.connect()
m = MetaData()
m.reflect(engine)
customers = m.tables["customers"]
_ = conn.execute(customers .insert(), insert)
conn.close()
其中 get_engine 只是使用用户/密码等配置创建一个引擎实例( sqlalchemy.engine.Engine )。
感谢任何帮助!
I have a working API that has a function of inserting records to the database. The problem is, it inserts any record on top, not checking for duplicates/whether the record already exists.
What would be the most performant way to do it with that plugging?
I am using SQLAlchemy as this is my company's standard (especially that we work on gcp) but I am not that familiar with that library, and searching I couldn't find anything useful.
My current code is:
def db_push(insert: dict)->dict:
def insert_results(results):
rows = []
for i in results:
rows.append(
{
"name": i["Name"],
"id": i["id"],
"amount": I["amount"],
"invoice" : I["invoice"],
"country" : i["Country"]
}
)
return rows
insert = insert_results(insert)
conn = engine.connect()
m = MetaData()
m.reflect(engine)
customers = m.tables["customers"]
_ = conn.execute(customers .insert(), insert)
conn.close()
where get_engine just creates an engine instance ( sqlalchemy.engine.Engine ) with user/pass etc configurations.
Appreciate any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论