使用Python中的变量与PostgreSQL进行通信

时间:2017-01-18 13:20:01

标签: python postgresql psycopg2

我一直在尝试在我的SQL命令中放置变量。但是,当我尝试这个时:

def interact_database(command):
    connection = psycopg2.connect("dbname=NAME user=NAME password=PASSWORD")
    cursor = connection.cursor()

    cursor.execute(command)
    connection.commit()

    results = None
    try:
        results = cursor.fetchall()
    except psycopg2.ProgrammingError:
        print("Connection failure.")
        pass

    cursor.close()
    connection.close()

    return results


def pick_question(type):
    if type == 'G':
        QuestionID = random.randint(1,38)
    elif type == 'Gr':
        QuestionID = random.randint(39,60)
    elif type == 'R':
        QuestionID = random.randint(61,89)
    else:
        QuestionID = random.randint(90,119)
    interact_database("SELECT Question FROM Questions WHERE Question_ID = %s")(QuestionID)

pick_question('G')

我收到此错误

psycopg2.ProgrammingError: syntax error at or near "%"
LINE 1: SELECT Question FROM Questions WHERE Question_ID = %s

我已经多次尝试谷歌搜索,但我读到的任何地方都应该有效。有人知道我在做错了吗?提前谢谢!

2 个答案:

答案 0 :(得分:4)

尝试将数据库连接api包装在自己的类中是一个常见的新错误。 总是导致这样的问题。所以不要

connection = psycopg2.connect("dbname=NAME user=NAME password=PASSWORD")
cursor = connection.cursor()

def pick_question(type, cursor):
    if type == 'G':
        QuestionID = random.randint(1,38)
    elif type == 'Gr':
        QuestionID = random.randint(39,60)
    elif type == 'R':
        QuestionID = random.randint(61,89)
    else:
        QuestionID = random.randint(90,119)

    cursor.execute("SELECT Question FROM Questions WHERE Question_ID = %s" , (QuestionID,))
    connection.commit()


pick_question('G', cursor)

答案 1 :(得分:0)

您尚未将变量传递给SQL查询。您所做的就是将 next 置于对interact_database功能的调用中。您需要修改该函数以接受数据,然后将其传递给cursor.execute;然后实际将数据传递给函数。所以:

def interact_database(command, params=None):
    ...
    cursor.execute(command, params)

...
interact_database("SELECT Question FROM Questions WHERE Question_ID = %s", (QuestionID,))