1

I am trying to insert a list of values into a single column and getting the following error:

postgresConnection = psycopg2.connect(
host='x',
user='x',
password='x',
database='x'
)
data = '[12, 37]'
sqlpoptable = ("INSERT INTO datas (conditions) VALUES (?);", data)
cursor.execute(sqlpoptable, data)
postgresConnection.commit()`          


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-36-fa661d7bfe6a> in <module>
    7 data = '[12, 37]'
    8 sqlpoptable = ("INSERT INTO datas (conditions) VALUES (?);", data)
    ----> 9 cursor.execute(sqlpoptable, data)
    10 postgresConnection.commit()

TypeError: argument 1 must be a string or unicode object: got tuple instead
wildplasser
  • 43,142
  • 8
  • 66
  • 109
c0lton
  • 61
  • 1
  • 9

2 Answers2

1

sqlpoptable should contain the query only, but you specified the data in it, too, so eventually you specified data twice.

Either do this:

data = '[12, 37]'
sqlpoptable = "INSERT INTO datas (conditions) VALUES (?);"
cursor.execute(sqlpoptable, data)

or this (semantically equivalent, just using a bit of syntactic sugar):

data = '[12, 37]'
sqlpoptable = ("INSERT INTO datas (conditions) VALUES (?);", data)
cursor.execute(*sqlpoptable)

BTW: You do not need to pass a trailing semicolon to psycopg2.

Christoph Thiede
  • 707
  • 10
  • 16
  • Thank you for your response, your suggestion makes since to me however I am receiving the following error: SyntaxError: syntax error at or near ")" LINE 1: INSERT INTO datas (conditions) VALUES (?); – c0lton Dec 30 '20 at 13:43
  • I think you used the wrong placeholder, it should be `%s`. Maybe the following questions and its answers could help you? https://stackoverflow.com/questions/8134602/psycopg2-insert-multiple-rows-with-one-query – Christoph Thiede Dec 31 '20 at 14:42
1

You can use a list for parameters such as

data = [[12],[37]]
cursor.executemany("INSERT INTO datas(conditions) VALUES (?)",(data))
postgresConnection.commit()

where executemany is more performant method than execute

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55