循环不适用于sql update语句(mysqldb)

时间:2017-09-18 20:15:55

标签: python mysql sql-update mysql-python glob

我有一个名为' 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中的一个将数据插入到表的所有列中,但我需要它根据哪个文件插入不同的数据代码当前正在运行。我无法弄清楚为什么会这样,因为我在objkey循环中定义了for filename in files。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

不要单独执行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)