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

标签 python mysql variables python-2.7 insert

我想将变量 bobdummyVar 插入到我的表 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()

最佳答案

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

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

或使用 variable argument syntax (a splat, *) :

cursor.execute(*loggit)

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

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

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

关于python - 使用 Python 插入变量 MySQL,不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16506643/

相关文章:

Mysql if语句忽略第一个条件

php - 替代 mysqli 中的 mysql_field_name

linux - 带有 grep 的 Bash 函数,使用 if 和 then 语句

bash - 从主机名分配变量

python - CSRF验证失败。请求中止。//Dajaxice,Ajax

python - 如何检查一个iterable是否可以再次被遍历?

python - 如何将 boto3 Dynamo DB 项目转换为 Python 中的常规字典?

javascript - 使用 Angular JS 从运行 MySQL 的 PHP 服务器获取数据时出错

c - C中静态全局变量和非静态全局变量的区别

python - sqlalchemy 寻找字符串形式的服务器版本,而不是类似字节的对象