问题
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