python正则表达式,字典没有插入到mysql中

时间:2014-07-13 17:24:15

标签: python mysql regex dictionary

我收到一本字典' p'从以下代码,但无法插入到mysql数据库中。请帮我将数据插入数据库。

字典是:[(' Casssandraw','烹饪'),(' Archanea','播放'),(&# 39; Adarshan',' Programming'),(' Leelal',' Baking')] 应存储在名称和爱好字段中。

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()  

1 个答案:

答案 0 :(得分:0)

&#39; p&#39;的价值是什么?我认为&#39; p&#39;是这样的:

print(p)
>>> [('Casssandraw', 'Cooking'), ('Archanea', 'Playing'), ('Adarshan', 'Programming'), ('Leelal', 'Baking')]

然后:

value_parm = ','.join(['(%s,%s)'] * len(p))
sql = 'INSERT INTO Details (Names, Hobby) VALUES %s' % value_parm
# print(sql)
# >>> INSERT INTO Details (Names, Hobby) VALUES (%s,%s),(%s,%s),(%s,%s),(%s,%s)
import itertools
flat_p = itertools.chain.from_iterable(p)
# flat_p is an iterable like ['Casssandraw', 'Cooking', 'Archanea', ...]
db.cursor().execute(sql, flat_p)
db.commit()