我正在尝试将字符串写入文件。此文件将是对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"]
将为无。但是,因为我有%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"]))
但那是两行代码。如果后来我意识到不止一个值可能是无?我必须检查每一个案例!我需要让这种动态。
感谢任何帮助。
答案 0 :(得分:3)
这个怎么样?
import org.json.*;
JSONObject o = new JSONObject(jsonString);
JSONArray arr = obj.getJSONArray("Attendance");
for (int i = 0; i < arr.length(); i++)
{
JSONObject b = arr.getJSONObject(i);
Iterator<?> keys = b.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
System.out.println(key+": "+b.get(key).toString());
}
}
答案 1 :(得分:2)
如果不添加引号,稍后用带引号的注释替换它(双重替换,但可以在一行中完成)?
row = {"comment": "abc"}
comment = row.get("comment") # Note, bracket lookup would have thrown a KeyError, not returning None
values = "%d, '%s', %s" % (1, "string_value", "'%s'" % comment if comment is not None else None)
print values
哪个会打印
1, 'string_value', 'abc'
或1, 'string_value', None
然后使用VALUES = (%s) % values
请注意,如果您只保留
,实际上甚至不需要将VALUES分成另一个替换comment = row.get("comment")
# In your string:
VALUES = (%s) % ("%d, '%s', %s" % (row["int_value"], row["string_value"], "'%s'" % comment if comment is not None else None))
这是一个基本的例子:
>>> comment = None
>>> 'Values = (%s)' % ("'%s'" % comment if comment is not None else None)
'Values = (None)'
>>> comment = "test"
>>> 'Values = (%s)' % ("'%s'" % comment if comment is not None else None)
"Values = ('test')"
>>> comment = "" # For empty comments, thanks to @Bharel for pointing this out
>>> 'Values = (%s)' % ("'%s'" % comment if comment is not None else None)
"Values = ('')"
答案 2 :(得分:2)
您可以使用任何python mysql模块及其游标选项
cursor.mogrify(query, args)
如果您已经在使用它。 它将根据类型正确地逃避一切。
如果你想手动完成,那么你可以做一个简单的
row['comment'] if row['comment'] is None else "'".join(['',row['comment'],''])
查询前的
答案 3 :(得分:0)
为什么不插入
if row["comment"] is not None:
row["comment"] = "'%s'" % row["comment"]
file.write(...
它为您提供了所需的自定义行为,不需要重复任何代码
答案 4 :(得分:0)
您可以尝试使用
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"] or 'NULL'))
答案 5 :(得分:0)
我会将repr(row["comment"])
与%s
一起使用。它为您提供字符串周围的引号,但仅保留None
字面值。
>>> 'VALUES (%s)' % repr(None)
'VALUES (None)'
>>> 'VALUES (%s)' % repr("string")
"VALUES ('string')"