私は 'testfolder'という2つのファイル - 'Sigurdlogfile'と '2004ADlogfile'を含むフォルダを持っています。各ファイルにはentries
という文字列のリストがあります。私は両方のコードを実行する必要があり、これを行うにはglob
を使用しています。私のコードは、各ファイルの辞書を作成し、辞書キーが格納されている正規表現を使用して抽出されたデータを、下のcommonterms
に格納します。次に、各辞書をmysqlテーブルに挿入します。これはうまくいっていますが、私の2番目のSQL文はどのように(ファイルごとに)挿入するのではないのですか?ループはSQLの更新ステートメント(mysqldb)のために働いていません
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()
問題は、2番目のSQL文で、それはobjkey
秒の一つだけからのテーブルのすべての列にデータが、私はどのファイルに応じて、異なるデータを挿入することが必要であることを挿入して終わるということですコードは現在実行中です。私はfor filename in files
のループの中にobjkey
を定義しているので、なぜこのことが分かりません。これをどうすれば解決できますか?
2番目のクエリは 'table'と' oldtable'の間には関係がありませんので、完全なクロスプロダクトを実行しています。 – Barmar
文字列置換を行う代わりに準備文を実行することを学ぶ必要があります。 – Barmar
@Barmarどういう意味ですか?それは古いテーブルから 'Sigurdlogfile'の正しいデータを挿入していますが、問題はそれがSigurdデータを2004ADから挿入しなければならない場所に挿入していることです。 –