我正在编写代码以更新数据库,我想获取提交后插入的行数,该怎么办?
for table, endpoint in ENDPOINTS.items():
url = BASE_URL + endpoint
response = get_response(url)
table_object = getattr(Base.classes, table)
self.add_missing_data(response, table_object, session)
session.commit()
print('Total rows added: {}'.format(xxxxx))
答案 0 :(得分:0)
如果add_missing_data
是您定义的方法,则只需返回在其中插入的行数即可。
def add_missing_data(self, ...)
rows = 0
for i in data:
# insert data code...
rows += 1
return rows
然后将它们总结一下。
total = 0
for table, endpoint in ENDPOINTS.items():
total += self.add_missing_data(response, table_object, session)
session.commit()
print('Total rows added: {}'.format(total))
如果您想要更动态的东西,可以对after_insert或before_insert使用sqlachemy事件
答案 1 :(得分:0)
引用this Q/A:
这是您的代码:
from sqlalchemy import create_engine
def add_mising_data(self, response, table_object, session):
con = create_engine(...)
# insert some data using
# con, response, table_object and session
result_proxy = con.execute("INSERT ...")
return result_proxy.rowcount # this is the number of inserted rows
# in your loop
total_num_row = 0
for table, endpoint in ENDPOINTS.items():
url = BASE_URL + endpoint
response = get_response(url)
table_object = getattr(Base.classes, table)
num_row = self.add_missing_data(response, table_object, session)
total_num_row = total_num_row + num_row
print (total_num_row) # <-- here you are