Psycopg2 - 并非所有参数都在字符串格式化期间转换
Psycopg2 - not all arguments converted during string formatting
每次触发 database_insert 函数时,我都试图将变量 test_text 的值插入到 Postgres 9.6 数据库中。
我正在使用 Python 3.6 和 psycopg2 v 2.7
如果我在没有占位符的情况下使用以下代码:例如将 %s 替换为 'test' 并删除 , (test_text) - 它按我预期的那样工作...
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()
然而,当函数尝试使用 %s 占位符插入 test_text 变量的值时,出现以下错误...
cur.execute("INSERT INTO test VALUES(%s);", (test_text))
TypeError: not all arguments converted during string formatting
任何关于我哪里出错的帮助将不胜感激!
这里有一个微妙的问题。
你需要一个逗号来组成一个元组,而不仅仅是 parens/brackets。
所以只需更改为:
cur.execute("INSERT INTO test VALUES(%s);", (test_text,))
而且你应该很好!
每次触发 database_insert 函数时,我都试图将变量 test_text 的值插入到 Postgres 9.6 数据库中。
我正在使用 Python 3.6 和 psycopg2 v 2.7
如果我在没有占位符的情况下使用以下代码:例如将 %s 替换为 'test' 并删除 , (test_text) - 它按我预期的那样工作...
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()
然而,当函数尝试使用 %s 占位符插入 test_text 变量的值时,出现以下错误...
cur.execute("INSERT INTO test VALUES(%s);", (test_text))
TypeError: not all arguments converted during string formatting
任何关于我哪里出错的帮助将不胜感激!
这里有一个微妙的问题。
你需要一个逗号来组成一个元组,而不仅仅是 parens/brackets。
所以只需更改为:
cur.execute("INSERT INTO test VALUES(%s);", (test_text,))
而且你应该很好!