在Python MySQLdb中包含DB函数调用executemany()
当我尝试运行如下语句时:
cursor.executemany("""INSERT INTO `test` (`id`,`data`,`time_added`)
VALUES (%s, %s, NOW())""", [(i.id, i.data) for i in items])
MySQLdb 似乎在 NOW() 中的 ) 上被阻塞,当它扩展要插入的行列表时,因为它将括号视为值块的末尾。也就是说,查询如下:
('1', 'a', NOW(), ('2','b', NOW(), ('3','c',NOW())
MYSQL 报告语法错误。相反,它们应该看起来像:
('1', 'a', NOW()), ('2','b', NOW()), ('3','c',NOW())
应该有某种方法可以逃避 NOW(),但我不知道如何。将 'NOW()' 添加到元组中不起作用,因为 NOW() 会被数据库引用并解释为字符串而不是函数调用。
通过使用当前时间戳作为默认值来解决这个问题不是一个选项——这是一个例子,我需要使用各种数据库函数来完成这种事情,而不仅仅是现在。
谢谢!
When I try to run statements like:
cursor.executemany("""INSERT INTO `test` (`id`,`data`,`time_added`)
VALUES (%s, %s, NOW())""", [(i.id, i.data) for i in items])
MySQLdb seems to choke on the ) in NOW(), when it expands the list of rows to be inserted because it sees that parenthesis as the end of the value block. That is, the queries look like:
('1', 'a', NOW(), ('2','b', NOW(), ('3','c',NOW())
And MYSQL reports a syntax error. Instead, they should look like:
('1', 'a', NOW()), ('2','b', NOW()), ('3','c',NOW())
There should be some way to escape the NOW(), but I can't figure out how. Adding 'NOW()' to the tuple doesn't work because then NOW() is quoted and interpreted by the DB as a string rather than a function call.
Working around this by using current timestamp as default value is not an option -- this is an example, I need to do this sort of thing with a variety of db functions, not just now.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
下面的方法远非理想,但不幸的是,这是我所知道的唯一方法。
这个想法是手动构建 SQL,使用
connection.literal
来转义你的参数:这看起来很糟糕,并且可能会让你起鸡皮疙瘩,但是如果你看看底层(在 /usr/ lib/pymodules/python2.6/MySQLdb/cursors.py) 在 MySQLdb 在 Cursors.executemany 中所做的事情,我认为这与该函数正在做的事情是一样的,减去了由于混合造成的正则表达式
cursors.insert_values
未正确解析嵌套括号。 (哎哟!)我刚刚安装了 oursql,它是 MySQLdb 的替代品,我很高兴报告
我们的sql按预期工作。
The method below is far from ideal, but, unfortunately, it is the only way I know.
The idea is to manually construct the SQL, using
connection.literal
to escape the arguments for you:This looks horrible, and may make your skin crawl, but if you look under the hood (in /usr/lib/pymodules/python2.6/MySQLdb/cursors.py) at what MySQLdb is doing in
cursors.executemany
, I think this is along the same lines as what that function is doing, minus the mixup due the regexcursors.insert_values
not correctly parsing the nested parentheses. (eek!)I've just installed oursql, an alternative to MySQLdb, and am happy to report that
works as expected with oursql.