python字典mysql不插入(python dictionary mysql not insert)

编程入门 行业动态 更新时间:2024-10-28 14:22:55
python字典mysql不插入(python dictionary mysql not insert)

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

字典是:[('Casssandraw','烹饪'),('Archanea','播放'),('Adarshan','编程'),('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()

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.

dictionary is :[('Casssandraw', 'Cooking'), ('Archanea', 'Playing'), ('Adarshan', 'Programming'), ('Leelal', 'Baking')] should be stored to Names and Hobby fields.

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

最满意答案

看起来你有一个包含名字/爱好而不是dict的元组列表:

您可以打开两个并插入:

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

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

更多推荐

本文发布于:2023-08-07 22:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466182.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   python   mysql   insert   dictionary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!