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

How to use variables to insert into tables from python to PostgreSQL

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

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

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.

 var1 = "x"
 var2 = datetime.datetime.now()
 curs.execute("INSERT INTO sometable (col1, col2) VALUES (%s, %s)", (var1,var2))

the manual