【发布时间】:2020-04-02 09:17:28
【问题描述】:
我在一个文件上运行 linux 终端命令“字符串”并将结果(一系列可读字符串)存储在一个变量中。结果也被写入文本文件。然后我需要将结果上传到数据库。问题是结果通常包含 ' 和 " 以不可预知的顺序排列的字符。这些会导致 SQL 错误。我尝试将 string.replace 替换为空字符串和 \ 转义。我也尝试过 """ 或 ' '' 围绕字符串但都不起作用,因为我不知道哪种类型的引号将是第一个。任何建议,将不胜感激。
fileName = filePath.rsplit('/', 1)[1]
stream = os.popen('strings ' + filePath)
output = stream.readlines()
file = open(filePath + "/" + fileName + "_StringsResults.txt", "w+")
for o in output:
file.write(str(o))
results += str(o)
file.close()
dsn = 'postgresql://###########@localhost:########/test?sslmode=disable'
conn = psycopg2.connect(dsn)
with conn.cursor() as cur:
cur.execute(
"UPSERT INTO test (testID) VALUES ('%s')" % (results))
conn.commit()
【问题讨论】:
-
你看过准备好的/参数化的sql吗?它们省去了清理变量输入的所有麻烦,因为你实际上并没有将它作为sql的一部分传递。相反,您使用占位符准备 sql,然后稍后传入参数。
-
我没有,但我会的。感谢您的提示。
-
当您将数据作为 sql 的一部分传递时,它们只是为您省去了在数据中转义特殊字符的麻烦
标签: python-3.x string cockroachdb