【发布时间】:2016-03-15 20:39:10
【问题描述】:
我正在尝试将字符串写入文件。该文件将是对 Microsoft 的 SQL 服务器的查询,因此它必须遵循特定的格式。这就是我的问题所在。
假设其余的代码是正确的,我的写方法是这样的:
file.write("INSERT INTO SAMPLE_TABLE (int_value, string_value, comment)\n"
"VALUES (%d, '%s', '%s')\n\n"
% (row["int_value"], row["string_value"], row["comment"]))
如您所见,我需要在%s 周围加上引号,因为这是查询的语法。我还应该提到我正在开发一个 GUI。用户可以选择输入评论。如果用户没有输入任何内容,row["comment"] 将为 None。但是,因为我在%s周围有引号,所以它会写'None',这将是数据库中与None相对的字符串,在数据库中转换为NULL,这就是我想要的。
我可以这样做:
if row["comment"] is None:
file.write("INSERT INTO SAMPLE_TABLE (int_value, string_value, comment)\n"
"VALUES (%d, '%s', %s)\n\n"
% (row["int_value"], row["string_value"], row["comment"]))
else:
file.write("INSERT INTO SAMPLE_TABLE (int_value, string_value, comment)\n"
"VALUES (%d, '%s', '%s')\n\n"
% (row["int_value"], row["string_value"], row["comment"]))
但那是两行代码。如果后来我意识到不止一个值可能是 None 怎么办?我必须检查每一个案例!我需要让这个动态化。
感谢任何帮助。
【问题讨论】:
标签: python sql python-3.x