Mayank
Mayank

Reputation: 2503

Inserting data in postgres using a python list

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

Upvotes: 0

Views: 899

Answers (2)

Yevgen Yampolskiy
Yevgen Yampolskiy

Reputation: 7180

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

Upvotes: 0

Craig Ringer
Craig Ringer

Reputation: 324325

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 ]

Upvotes: 1

Related Questions