【发布时间】:2016-11-12 17:55:09
【问题描述】:
我有一个 python 脚本,它将 csv 作为输入并将其数据插入数据库。我正在从生成此 CSV 的 php 脚本中调用此脚本。如果我从终端调用 python 脚本并将 csv 传递给它,它可以完美运行,但是如果我使用 php 从 php 调用它
exec('python bulk_metadata_ingest_dev.py '. $metadataCSV);
插入表时会引发 mysql 错误。
_mysql_exceptions.ProgrammingError: (1064, '您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,了解在 \'text to insert""\' 附近使用的正确语法第 1 行')
查询哪个报错:
cursor = db.query("insert into test_table(asset_type, attribute_id, asset_title, is_publishable, owner) values(\""+str(mediaAssetTypeDict[sample_content.media_type.lower()])+"\", \""+str(attributeId)+"\", \""+str(assetTitle)+"\", \""+str(publishAssets)+"\", \""+str(sample_content.content_owner)+"\" )")
在python中我不知道如何处理这个问题。 提前致谢
【问题讨论】:
-
不应该 \"" 是 \"\" 吗?只是一个疯狂的猜测。
-
你插入数据中的值是什么?
-
@antonio_antuan 提出的有趣问题,如果您通过使用
cursor = db.query("insert into test_table(asset_type, attribute_id, asset_title, is_publishable, owner) values('"+str(mediaAssetTypeDict[sample_content.media_type.lower()])+"', '"+str(attributeId)+"', '"+str(assetTitle)+"', '"+str(publishAssets)+"', '"+str(sample_content.content_owner)+"')")来减少逃跑的需要怎么办?我知道数据库,不喜欢字符串文字周围的双引号... -
@Dilettant 谢谢伙计 它奏效了。但对我来说,为什么当我使用相同的输入文件直接从终端运行这个 python 脚本时它工作正常,这对我来说仍然是个谜。
-
如果我有从 python 脚本写入数据库的“这样的任务”,我接下来会稍微简化和保护代理,即尝试准备好的语句,而不是将字符串构造为“查询" 在调用运算符的括号内,但可能会构建一个元组,然后填写准备好的语句的“空白”。当接受来自信任边界之外的输入时,这减少了许多分层的单引号、双引号字符串调用洋葱皮,更明确,不像表示状态操作,并且更安全。但现在好了,让你继续。感谢您的反馈。