使用Python插入变量MySQL,无法正常工作 [英] Inserting Variables MySQL Using Python, Not Working

查看:112
本文介绍了使用Python插入变量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))

这篇关于使用Python插入变量MySQL,无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆