2014-07-13 89 views
0

我從下面的代碼中獲得了一個字典'p',但無法插入到mysql數據庫中。請幫助我將數據插入到數據庫中。 (''Casssandraw','Cooking'),('Archanea','Playing'),('Adarshan','Programming'),('Leelal','Baking')] 應該是: 應該是: 應該是: 存儲到名稱和業餘愛好字段。python字典mysql不插入

Name  Hobby 
Cassandraw Cooking 
Archanea Playing 
...  ... 

計劃:

import MySQLdb 
import re 
db = MySQLdb.connect(host="localhost", # your host, usually localhost 
        user="root", # your username 
         passwd="mysql", # your password 
         db="sakila") # n 

with open('qwer2.txt','r') as file, db as cursor: 
    f = open('qwer2.txt', 'r') 

    lines = f.readlines() 

    for x in lines: 
     p=re.findall(r'(?:name is|me)\s+(\w+).*?(?:interest|hobby)\s+is\s+(\w+)',x, re.I) 
     print p 

     cursor.execute(
     '''INSERT INTO Details (Names, Hobby) 
      VALUES (%s, %s)''', 
     (name, hobby))#<-donot know what to provide 
db.commit() 
+0

你是否收到一些錯誤? –

+0

是的,我得到錯誤作爲名稱未定義,但不知道要提供什麼,而不是名稱和愛好! – user3830379

+0

你從哪裏得到你的正則表達式的名字和愛好?你的字典也在哪裏? –

回答

1

看起來你有一個包含名稱/愛好不是字典元組的列表:

可以解開兩個插入:

for name, hobby in p: # I am presuming p is the list you posted in your question 
    cursor.execute(
     '''INSERT INTO Details (Names, Hobby) 
      VALUES (%s, %s)''', 
     (name, hobby))#<-donot know what to provide 


for name,hobby in p: 
    print name,hobby 
Casssandraw Cooking 
Archanea Playing 
Adarshan Programming 
Leelal Baking 
+0

哇,這就是我昨天搜索的整個過程!非常感謝你,現在它工作! – user3830379

+0

沒問題,不客氣。 –