[英]In pypyodbc, How to query a table for its distinct values, truncate old table and append the distinct values to the empty table
I have a table that for whatever reason has some dupes after a process runs.我有一张桌子,无论出于何种原因,在进程运行后都有一些欺骗。 Each row should be a distinct report.
每一行都应该是一个不同的报告。 I'm trying to do this with a for look on the cursor object after doing the.fetchall method and it is working somewhat.
在执行 .fetchall 方法之后,我正在尝试通过查看 cursor object 来做到这一点,并且它有点工作。 But it only inserts one row.
但它只插入一行。
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()
If I just print "row" within the for loop I get the list of tuples with all the fields and values I need for my table but I'm not sure how to pass these back into the empty table, all of the rows, not just one.如果我只是在 for 循环中打印“行”,我会得到包含表所需的所有字段和值的元组列表,但我不确定如何将这些返回到空表中,所有行,而不是只有一个。 Why am I getting only one?
为什么我只有一个?
You are truncating (emptying) the table each time you iterate through your for
loop.每次遍历
for
循环时,您都在截断(清空)表。 Therefore, when the loop finishes, your table will only contain the last row you inserted.因此,当循环结束时,您的表将只包含您插入的最后一行。 You probably want to execute the
TRUNCATE TABLE
just once, before you enter the loop.在进入循环之前,您可能只想执行一次
TRUNCATE TABLE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.