Inserting Variables MySQL Using Python, Not Working(使用 Python 插入变量 MySQL,不工作)
问题描述
我想将变量 bob
和 dummyVar
插入到我的表 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,不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Python 插入变量 MySQL,不工作


- 更改自动增量起始编号? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01