gpt4 book ai didi

python - 循环不适用于 sql 更新语句 (mysqldb)

转载 作者:行者123 更新时间:2023-11-29 10:36:38 25 4
gpt4 key购买 nike

我有一个名为“testfolder”的文件夹,其中包含两个文件——“Sigurdlogfile”和“2004ADlogfile”。每个文件都有一个名为entries 的字符串列表。我需要在它们两个上运行我的代码,并使用 glob 来执行此操作。我的代码为每个文件创建一个字典,并存储使用正则表达式提取的数据,其中字典键存储在下面的 commonterms 中。然后它将每个字典插入到 mysql 表中。它成功地完成了所有这些操作,但我的第二个 sql 语句没有按照应有的方式插入(每个文件)。

import glob
import re
files = glob.glob('/home/user/testfolder/*logfile*')

commonterms = (["freq", "\s?(\d+e?\d*)\s?"],
["tx", "#txpattern"],
["rx", "#rxpattern"], ...)

terms = [commonterms[i][0] for i in range(len(commonterms))]
patterns = [commonterms[i][1] for i in range(len(commonterms))]

def getTerms(entry):
for i in range(len(terms)):
term = re.search(patterns[i], entry)
if term:
term = term.groups()[0] if term.groups()[0] is not None else term.groups()[1]
else:
term = 'NULL'
d[terms[i]] += [term]
return d

for filename in files:
#code to create 'entries'
objkey = re.match(r'/home/user/testfolder/(.+?)logfile', filename).group(1)

d = {t: [] for t in terms}

for entry in entries:
d = getTerms(entry)

import MySQLdb
db = MySQLdb.connect(host='', user='', passwd='', db='')
cursor = db.cursor()
cols = d.keys()
vals = d.values()

for i in range(len(entries)):
lst = [item[i] for item in vals]
csv = "'{}'".format("','".join(lst))
sql1 = "INSERT INTO table (%s) VALUES (%s);" % (','.join(cols), csv.replace("'NULL'", "NULL"))
cursor.execute(sql1)

#now in my 2nd sql statement I need to update the table with data from an old table, which is where I have the problem...

sql2 = "UPDATE table, oldtable SET table.key1 = oldtable.key1,
table.key2 = oldtable.key2 WHERE oldtable.obj = %s;" % repr(objkey)
cursor.execute(sql2)

db.commit()
db.close()

问题是,在第二个sql语句中,它最终仅从其中一个objkey将该数据插入到表的所有列中,但我需要它根据不同的情况插入不同的数据代码当前正在哪个文件上运行。我不明白为什么会这样,因为我已经在 for filename in files 循环中定义了 objkey 。我该如何解决这个问题?

最佳答案

不要单独执行INSERTUPDATE,而是将它们一起执行以合并旧表中的字段。

for i in range(len(entries)):
lst = [item[i] for item in vals]
csv = "'{}'".format("','".join(lst))
sql1 = """INSERT INTO table (key1, key2, %s)
SELECT o.key1, o.key2, a.*
FROM (SELECT %s) AS a
LEFT JOIN oldtable AS o ON o.obj = %s""" % (','.join(cols), csv.replace("'NULL'", "NULL"), repr(objkey))
cursor.execute(sql1)

关于python - 循环不适用于 sql 更新语句 (mysqldb),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46287531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com