[英]python dictionary mysql not insert
I obtaines a dictionary 'p' from the following code,but cannot able to insert into the mysql database.please help me to insert the datas into database. 我从以下代码中获得了字典'p',但是无法插入到mysql数据库中。请帮助我将数据插入数据库中。
dictionary is :[('Casssandraw', 'Cooking'), ('Archanea', 'Playing'), ('Adarshan', 'Programming'), ('Leelal', 'Baking')] should be stored to Names and Hobby fields. 字典是:[('Casssandraw','Cooking'),('Archanea','Playing'),('Adarshan','Programming'),('Leelal','Baking')]应该存储到名称和爱好领域。
Name Hobby
Cassandraw Cooking
Archanea Playing
... ...
Program: 程序:
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()
It looks like you have a list of tuples containing name/hobby not a dict: 看起来您有一个包含名称/爱好而不是字典的元组列表:
You can unpack the two and insert: 您可以打开两个包装,然后插入:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.