【问题标题】:How to use variables to insert into tables from python to PostgreSQL如何使用变量插入从 python 到 PostgreSQL 的表
【发布时间】:2017-08-27 04:45:55
【问题描述】:

我是 python 和 SQL 的新手。 我最终想要做的是用户键入一个值以插入到 PostgreSQL 中的表中。 我已经尝试了一些我能找到的方法,

但我一直无法成功插入。 这就是我现在拥有的:

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


【解决方案1】:
 var1 = "x"
 var2 = datetime.datetime.now()
 curs.execute("INSERT INTO sometable (col1, col2) VALUES (%s, %s)", (var1,var2))

the manual

【讨论】:

    猜你喜欢
    • 2017-11-21
    • 2017-09-17
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    相关资源
    最近更新 更多