0

I was wondering if anyone could help me figure out why the data that my python script has gathered is not being input into the mysql database properly

Here is my code

/*** index is a dictionary that has the struture: 
 index = {links:[words], links: [words],.......} ***/
#There are multiple items in words
for k, v in index.iteritems():
 links = str(k)
 words = str(v) [1:-1]
 import MySQLdb
 db = MySQLdb.connect("localhost","root","","my_db" )
 cursor = db.cursor()
 try:
 cursor.execute(('insert into SITE(url, keywords) values("%s", "%s")' % \
 (links,words)))
 db.commit()
 except:
 db.rollback()
db.close()

Each row in my table should have two feilds: url and keywords Instead of insterting 6 rows it only inserts two. Please help?!

asked Nov 9, 2014 at 10:27
1
  • please show the contents of ´index´ Commented Nov 9, 2014 at 10:49

1 Answer 1

1

Perhaps there is a problem, because you open a new connection for every item. Then you shouldn't format values into a SQL-statement, use parameters instead. Third, you shouldn't ignore exceptions, because then, you cannot figure out, what's going wrong. The representation of a list is nothing, to work with in production code, use join instead

import logging
import MySQLdb
db = MySQLdb.connect("localhost","root","","my_db" )
for links, words in index.iteritems():
 cursor = db.cursor()
 try:
 cursor.execute('insert into SITE(url, keywords) values(%s, %s)', (links, ','.join(words)))
 db.commit()
 except Exception:
 logging.exception('insert went wrong')
 db.rollback()
db.close()
answered Nov 9, 2014 at 10:52
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.