代码之家  ›  专栏  ›  技术社区  ›  Mark Smith

Psycopg2-在字符串格式化期间并非所有参数都已转换

  •  6
  • Mark Smith  · 技术社区  · 7 年前

    每次触发database\u insert函数时,我都试图将变量test\u text的值插入到Postgres 9.6数据库中。

    我正在使用Python 3.6和psycopg2 v 2.7

    如果我使用以下不带占位符的代码:例如,用“test”替换%s并删除,(test\u 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\u文本变量的值时,我得到以下错误。。。

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

    如果您能帮我解决这个问题,我们将不胜感激!

    1 回复  |  直到 7 年前
        1
  •  15
  •   mechanical_meat nazca    7 年前

    这里有一个微妙的问题。

    你需要一个逗号来组成元组,而不仅仅是括号。

    因此,只需更改为:

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

    你应该表现得很好!