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

2022-01-09 00:00:00 python python-2.7 variables insert mysql

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

I want to insert the variable bob, and dummyVar into my table, logger. Now from what I can tell all I should need to do is, well what I have below, however this doesn't insert anything into my table at all. If I hard-code what should be written (using 'example' then it writes example to the table, so my connection and syntax for inserting is correct to this point). Any help would be more than appreciated!

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

推荐答案

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

You need to pass the SQL statement and the parameters as separate arguments:

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

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

cursor.execute(*loggit)

您的版本尝试传入一个包含 SQL 语句和绑定参数的元组作为唯一参数,而 .execute() 函数希望只找到 SQL 语句字符串.

Your version tries to pass in a tuple containing the SQL statement and bind parameters as the only argument, where the .execute() function expects to find just the SQL statement string.

更常见的做法是将两者分开,也许只将 SQL 语句存储在一个变量中:

It's more usual to keep the two separate and perhaps store just the SQL statement in a variable:

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

相关文章