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
5
  • You need to convert the list into a string first. Try something like this into a variable. ', '.join(data) Commented Dec 30, 2020 at 13:25
  • @c0lton: What's the database type for column conditions, data could be interpreted as a string or list of integers ? Commented Dec 30, 2020 at 17:51
  • @Maurice Meyer the data type is integer Commented Dec 30, 2020 at 17:58
  • Isn't @Barbaros Özhan answer working ? Commented Dec 30, 2020 at 23:54
  • @Maurice Meyer Yes, just accepted the answer as that is what worked for my particular situation. Thanks! Commented Dec 31, 2020 at 4:43

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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 (?);
I think you used the wrong placeholder, it should be %s. Maybe the following questions and its answers could help you? stackoverflow.com/questions/8134602/…

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.