【发布时间】:2017-08-27 04:45:55
【问题描述】:
我是 python 和 SQL 的新手。 我最终想要做的是用户键入一个值以插入到 PostgreSQL 中的表中。 我已经尝试了一些我能找到的方法,
- https://www.postgresql.org/docs/9.1/static/plpgsql-structure.html
- http://www.java2s.com/Code/PostgreSQL/Postgre-SQL/UsingavariableinanINSERT.htm
但我一直无法成功插入。 这就是我现在拥有的:
import psycopg2
from config import config
def create_tables(a):
""" create tables in the PostgreSQL database"""
commands = (
"""
SET num 10,
INSERT INTO Hotel_A (date, Suite, StandardKing) VALUES ('2017-09-12', num, 3)
""",
"""
INSERT INTO Hotel_A (date, Suite, StandardKing) VALUES ('2017-09-29', 5, 3)
""",
"""
INSERT INTO Hotel_A (date, Suite, StandardKing) VALUES ('2017-09-23', 5, 3)
"""
)
conn = None
try:
# read the connection parameters
params = config()
# connect to the PostgreSQL server
conn = psycopg2.connect(**params)
cur = conn.cursor()
# create table one by one
for command in commands:
cur.execute(command)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
HotelASuite = 10
if __name__ == '__main__':
create_tables(HotelASuite)
我想做 num = HotelASuite 这是我的目标。
非常感谢您的帮助! 我正在使用 Python 2.7 和 PostgreSQL 9.6。
【问题讨论】:
-
能否解释一下您的问题
-
在问题中包含代码,而不是指向它的链接。换句话说,产生一个minimal reproducible example。查看例如this Q/A 以了解如何使用占位符。最后,永远不要手动格式化字符串或将值连接到查询。
-
所以当我插入这样的值时,INSERT INTO Hotel_A (date, Suite, StandardKing) VALUES ('2017-09-12', 5, 3),而不是写实际值,我想使用变量。所以我希望它看起来像 INSERT INTO Hotel_A (date, Suite, StandardKing) VALUES (date, int1, int2) 其中 date、int1 和 int2 实际上是 2017-09-12、5 和 3。这有意义吗?
-
是的。查看上一条评论中链接的问题。您正在寻找占位符。另请阅读有关如何传递变量的 psycopg2 文档:initd.org/psycopg/docs/…。再一次,不要自己使用任何形式的字符串格式化。这包括 f 字符串、
str.format()和旧的 % 格式。
标签: python postgresql psycopg2