如何使用变量插入从python到PostgreSQL的表中

2024-10-01 09:18:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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这是我的目标。在

非常感谢你的帮助!。 我使用的是python2.7和postgresql9.6。在


Tags: theconfigtablesdatepostgresqlcreateconnhotel