[英]In pypyodbc, How to query a table for its distinct values, truncate old table and append the distinct values to the empty table
我有一张桌子,无论出于何种原因,在进程运行后都有一些欺骗。 每一行都应该是一个不同的报告。 在执行 .fetchall 方法之后,我正在尝试通过查看 cursor object 来做到这一点,并且它有点工作。 但它只插入一行。
import pypyodbc
conn_str = ('Driver={SQL Server};Server=*****************;Trusted_Connection=yes;')
con = pypyodbc.connect(conn_str)
cur = con.cursor()
cur.execute("SELECT DISTINCT TDate, Report, Records, Status from Elig_Own.DST_Report_Status_Test")
rows = cur.fetchall()
for row in rows:
TDate = row[0] # first item in the tuple iterable
Report = row[1] # Second
Records = row[2] # third
Status = row[3] # fourth
cur.execute("truncate table Elig_own.DST_Report_Status_Test")
cur.execute('''INSERT into Elig_Own.DST_Report_Status_Test (TDate, Report, Records, Status)
VALUES (?, ?, ?, ?)''',(TDate, Report, Records, Status))
con.commit()
con.close()
如果我只是在 for 循环中打印“行”,我会得到包含表所需的所有字段和值的元组列表,但我不确定如何将这些返回到空表中,所有行,而不是只有一个。 为什么我只有一个?
每次遍历for
循环时,您都在截断(清空)表。 因此,当循环结束时,您的表将只包含您插入的最后一行。 在进入循环之前,您可能只想执行一次TRUNCATE TABLE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.