2013-07-15 78 views
0

在下面的例子中,我設法打印了那些我想插入到mysql表中的sql值。 我該如何真正執行該聲明?在mysql中插入值

import re 
import MySQLdb 

s = "Jul 15 12:12:51 whitelist logger: 1|999999999999|id:d9faff7c-4016-4343-b494-37028763bb66 submit date:1307130919 done date:1307130919 stat:DELIVRD err:0|L_VB3_NM_K_P|1373687445|vivnel2|L_VB3_GH_K_P|promo_camp1-bd153424349bc647|1" 

logger_re = re.compile(
"logger: ([^ ]+)\ 
submit date:(\d+)\ 
done date:(\d+)\ 
stat:(.+)\ 
err:(.+)$") 

myvalues = logger_re.search(s).groups() 

db = MySQLdb.connect(host="localhost", # your host, usually localhost 
        user="root", # your username 
         passwd="passwd", # your password 
         db="test") # name of the data base 

# you must create a Cursor object. It will let 
# you execute all the query you need 
cur = db.cursor() 

# cur.execute(insert into test.weblogs (output of myvalues)) 

這些值需要從文本文件中提取。通常是/ var/log/messages中

回答

2

這個例子應該有助於

閱讀您的問題後,很難說究竟是你的問題(格式化查詢,提交過程?)

try: 
    cur.execute("INSERT INTO MyTable (id,somerow) VALUES (%s, %s)" % ("someid", "somerow")) 
    db.commit() 
except MySQLdb.Error, e: 
    print e[0], e[1] 
    db.rollback() 
+0

必須逃脫數據也... –