Psycopg2 - not all arguments converted during string formatting

可紊 提交于 2020-12-25 10:04:24

问题


I'm trying to insert the value of the variable test_text into a Postgres 9.6 database, each time the database_insert function is triggered.

I'm using Python 3.6 and psycopg2 v 2.7

If I use the below code without the placeholder: e.g replace %s with 'test' and remove , (test_text) - it works as I would expect...

def database_insert(update):

    test_text = 'This is some test text'

    with psycopg2.connect("DB CONNECTION DETAILS ARE HERE'") as conn:

        cur = conn.cursor()

        cur.execute("INSERT INTO test VALUES(%s);", (test_text))

        conn.commit()

        cur.close()

    conn.close()

However when the function trys to insert the value of the test_text variable using the %s placeholder, I get the error below...

cur.execute("INSERT INTO test VALUES(%s);", (test_text))
TypeError: not all arguments converted during string formatting

Any help on where I am going wrong with this will be much appreciated!


回答1:


There's a subtle issue here.

You need a comma to make a tuple not just the parens/brackets.

So simply change to:

cur.execute("INSERT INTO test VALUES(%s);", (test_text,))

And you should be good!



来源:https://stackoverflow.com/questions/47956425/psycopg2-not-all-arguments-converted-during-string-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!