小编典典

使用Python插入变量MySQL,不起作用

mysql

我想插入变量bob,并dummyVar到我的桌前logger。现在,从我可以告诉我的所有信息中,我应该做的就是,下面是我所要做的,但是这根本不会在我的表中插入任何内容。如果我对应该写的内容进行硬编码(使用'example'它将示例写到表中,那么到目前为止我的连接和语法正确)。任何帮助将不胜感激!

conn = mysql.connector.connect(user='username', password='password!',
                              host='Host', database='database')

cursor = conn.cursor()

bob = "THIS IS AN EXAMPLE"
dummyVar = "Variable Test"

loggit = ("""
        INSERT INTO logger (logged_info, dummy)
        VALUES
            (%s, %s)
    """, (bob, dummyVar))

cursor.execute(loggit)
conn.commit()

我也尝试过这个:

loggit = ("""
        INSERT INTO logger (logged_info, dummy)
        VALUES
            (%(bob)s,(Hello))
    """, (bob))

和:

bob = "THIS IS AN EXAMPLE"
dummyVar = "Variable Test"

loggit = ("""
        INSERT INTO logger (logged_info, dummy)
        VALUES
            (%s, %s)
    """, (bob, dummyVar))

cursor.execute(loggit, (bob, dummyVar))
conn.commit()


cursor.execute(loggit, (bob, dummyVar))

conn.commit()

阅读 516

收藏
2020-05-17

共1个答案

小编典典

您需要将SQL语句和参数作为单独的参数传递:

cursor.execute(loggit[0], loggit[1])

或使用可变参数语法(splat
*

cursor.execute(*loggit)

您的版本尝试传入包含SQL语句的元组,并将绑定参数作为唯一参数,.execute()函数希望在其中仅查找SQL语句字符串。

通常将两者分开并可能仅将SQL语句存储在变量中:

loggit = """
        INSERT INTO logger (logged_info, dummy)
        VALUES
            (%s, %s)
    """
cursor.execute(loggit, (bob, dummyVar))
2020-05-17