我想在使用python的postgres插入查询中插入几个变量。我无法围绕如何使用字符串格式。插入带变量的查询postgresql python
例如,这工作得很好:
cursor.execute('''CREATE TABLE %s
(id SERIAL PRIMARY KEY,
sender varchar(255) not null,
receiver varchar(255) not null,
message varchar(255))''' %username)
为做到这一点:
cursor.execute('''INSERT INTO test (sender, receiver, message)
VALUES(%s,%s,%s)''', (sender, receiver,message))
我的问题是,我想有表名作为变量太多。我曾尝试:
cursor.execute('''INSERT INTO %s (sender, receiver, message)
VALUES(%s,%s,%s)''' %username, (sender, receiver, message))
我得到以下错误:
TypeError: not enough arguments for format string
,我感到我必须以某种方式改变了括号,但我不知道怎么办。
在此先感谢。
编辑:
选择从这个psycopg2其工作完全不同的方法。
用: cursor.execute(“INSERT INTO {}(发送者({},{},{})。格式(username,“one”,“two”,“three”)) 我得到了: > psycopg2.ProgrammingError:列“one”不存在 LINE 1:... SERT INTO测试(发送者,接收者,消息)VALUES(一,二,th ... –
是啊,应该工作 –
查看我的回复以上 –