Psycopg2 - 并非所有参数都在字符串格式化期间转换 [英] Psycopg2 - not all arguments converted during string formatting

查看:78
本文介绍了Psycopg2 - 并非所有参数都在字符串格式化期间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次触发 database_insert 函数时,我都试图将变量 test_text 的值插入到 Postgres 9.6 数据库中.

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.

我使用的是 Python 3.6 和 psycopg2 v 2.7

I'm using Python 3.6 and psycopg2 v 2.7

如果我使用下面没有占位符的代码:例如,将 %s 替换为 'test' 并删除 , (test_text) - 它按我的预期工作......

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()

但是,当函数尝试使用 %s 占位符插入 test_text 变量的值时,我收到以下错误...

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!

推荐答案

这里有一个微妙的问题.

There's a subtle issue here.

您需要一个逗号来制作元组,而不仅仅是括号/括号.

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

所以只需更改为:

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

你应该很好!

这篇关于Psycopg2 - 并非所有参数都在字符串格式化期间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆