我有脚本可以读取数据并进行转换并使用 python 插入数据库
但是转换后的数据正在循环插入,因此当我尝试获取cursor.rowcount时,它显示每个插入而不是最终计数
下面是我尝试过的脚本
try:
conn = dbapi.connect(
address="sapb101.sap.shome.net",
port=30015,
user="***",
password="***",
databasename='B1Q'
)
print("Succesful Connection to Hana Dev")
except:
print("Unsuccesful Connection to Hana Dev")
cur = conn.cursor ()
try:
del_query = '''
delete from "SAPTOM"."EL.ps.Tech::tbl.IBDbounrend_PY" where "LoadDt" = to_char(now(), 'YYYYMMDD')
'''
cur.execute(del_query)
print('number of rows deleted', cur.rowcount)
except Exception as e:
print("Error deleting query:", e)
query = '''
#select query
'''
cur.execute(query)
data = cur.fetchall()
number_rows = f"Total number of rows in table: {len(data)}\n"
print(number_rows# 65 rows
for row in data:
LoadDt = row[0]
#print(LoadDt)
FiscalWeek = row[1]
InboundCaseVol = row[2]
OutboundCaseVol6WCH =row[3]
OutboundCaseVol6WWC =row[4]
#print(LoadDt,FiscalWeek,InboundCaseVol,OutboundCaseVol6WCH,OutboundCaseVol6WWC)
try:
tgt_query = '''INSERT INTO"SAPTOM"."EL.ps.Tech::tbl.IBDbounrend_PY"("LoadDt","FiscalWeek","InboundCaseVol","OutboundCaseVol6WCH","OutboundCaseVol6WWC") VALUES (?,?,?,?,?) '''
val = (LoadDt,FiscalWeek,InboundCaseVol,OutboundCaseVol6WCH,OutboundCaseVol6WWC)
cur.execute(tgt_query, val)
conn.commit()
#print(cur.rowcount)
number_rows_inser = f'Number of Records inserted successfully: {cur.rowcount}\n'
except Exception as e:
print("Error inserting data:", e)
当我尝试打印 cur.rowcount 时,它每次都给我 1
以下是输出
成功插入的记录数:1
成功插入的记录数:1
成功插入的记录数:1
但我想要如下输出:
成功插入的记录数:65条
请在这里提出您的想法,帮助我!
您可以使用枚举函数来获取迭代的索引并获取迭代的长度,这将获得插入的总行数
count = None
for index, row in enumerate(data):
count = index
number_rows_inser = f'Number of Records inserted successfully: len(count)\n'