0

我想将变量bob, 和dummyVar插入我的表中,logger. 现在,据我所知,我需要做的就是,我在下面有什么,但这根本不会在我的表格中插入任何东西。如果我对应该写入的内容进行硬编码(使用'example'then 它将示例写入表中,因此我的插入连接和语法在这一点上是正确的)。任何帮助将不胜感激!

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()
4

1 回答 1

4

您需要将 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))
于 2013-05-12T11:16:49.987 回答