0

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

1 Answer 1

0

What's the value of 'p'? I assume 'p' is something like:

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

Then:

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.