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

时间:2017-08-27 04:45:56

标签: python postgresql psycopg2

我是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。

1 个答案:

答案 0 :(得分:1)

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

请参阅the manual