0

I want to enter a python list into an insert query and enter data into postgres, I am using executemany but still getting an error "TypeError: not all arguments converted during string formatting"

twitter_data = ['eOc6ZEQiNCo', u'TYihcUfotnM', u'7vneoA-vY8U', '73RRIEXsdyE']    
query = "INSERT INTO videograbber (video_id) VALUES (%s)"   
cur.executemany("INSERT INTO videograbber (video_id) VALUES (%s)",[twitter_data])
con.commit()

Can someone please tell me what I am doing wrong here

2
  • What error/problem are you getting? Commented Apr 3, 2014 at 4:42
  • I am getting this error- TypeError: not all arguments converted during string formatting" Commented Apr 3, 2014 at 4:49

2 Answers 2

1

Your list must be a list of tuples.

You haven't shown what the value of twitter_data is, but I suspect it's a string.

You want something like:

twitter_data = [ ('video_id_1',), ('video_id_2',) ]

Note the trailing commas, making these 1-tuples, instead of just parentheses around an expression. This is a 2-element list of 1-tuples containing (str), so when psycopg2 iterates the tuples within the list it gets the expected one element per tuple.

If you just wrote [ ('video_id_1'), ('video_id_2') ], you'd be producing a 2-element list containing two str objects. These are iterable, so psycopg2 will attempt to iterate them, converting each character as a a query parameter. It will have fewer parameters than characters, so it'll produce the error you showed.

You can convert a list of str into a list of 1-tuples of str with a list comprehension, e.g.:

twitter_data_tuples = [ (x,) for x in twitter_data ]
Sign up to request clarification or add additional context in comments.

Comments

0

You use "INSERT INTO videograbber (video_id) VALUES (%s)", but %s is a formatting tag. Should be something like "INSERT INTO videograbber (video_id) VALUES (?)"

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.