我在python中查询MySQL数据库并选择一个布尔值 - 所以MySQL的响应是字符串'True'或'False'。我想基于MySQL的布尔值执行更多代码。
E.g。
data = 'False' # assume this is what was returned by MySQL.
if data:
print 'Success' #really this would be where I would execute other if True.
else:
print 'Fail' #really this would be where I would execute other code if False
但我不能这样做,因为
if data:
将始终返回True
那么如何将MySQL返回的字符串转换为python中的布尔值?
目前我有:
data = 'False' # assume this is what was returned by MySQL.
if data == 'True':
print 'Success'
else:
print 'Fail'
我相信在python中必须有更好的方法来做到这一点 - 可能有一些我想念的简单。
答案 0 :(得分:2)
MySQL中的布尔值是TINYINT(1)。检查1或0可能有效
答案 1 :(得分:2)
如果列始终是实际字符串"False"
或"True"
之一(而不是整数或其他内容),那么我建议使用以下字符:
value = {'False' : False, 'True' : True}[data]
答案 2 :(得分:2)
如果您的数据库连接不知道如何为您转换值,那么您需要使用更好的值。这不应该是你自己需要做的事情。如果这些不是实际的布尔值,而只是一个int列,你只存储0或1,那么你应该修复你的架构。或者,如果你总是得到'True'和'False'的值,也许你不小心将它转换成某个字符串?
答案 3 :(得分:2)
您可以找到MySQLDdb转换MySQLdb目录中的converters.py文件中的值的位置。
这是处理bool的片段:
conversions = {
...
types.BooleanType: Bool2Str,
...
}
Bool2Str功能:
def Bool2Str(s, d): return str(int(s))
如果您想要不同的行为,请导入转换字典并进行更改。
答案 4 :(得分:0)
你的解决方案实际上还不错,但也有其他选择:
如果您使用的是Python 2.5或更高版本,则可以缩短if语句:
print 'Success' if data == 'True' else 'Fail'
如果您发现自己经常重复检查,可以考虑为其编写一个函数,使其更具可读性:
def is_true(mysql_boolean):
if mysql_boolean == "True":
return True
else:
return False
# now you can use this:
if is_true(data):
# this is really going to be more than one line of code anyway.
# or maybe a function call, in which your solution might be enough.
print "Success"
else:
print "Fail"
你可以用字典实现同样的目的,但我觉得这并不优雅:
mysql_bool = {'True': True, 'False': False}
if mysql_bool[data]:
print "Success"
那就是说,你用什么来连接数据库?可能有一种方法可以直接从那里获得一个bool。请更新您的问题!
答案 5 :(得分:0)
它处理MySQLdb返回的方式。
if data == '\x01':
print 'Success'
else:
print 'Fail'
已验证这适用于Python 3.6
if data == b'\x01':
print('Success')
else:
print('Fail')
答案 6 :(得分:0)
您可以使用ord
返回表示Unicode的整数。
示例:
if ord(data):
print("True")
if not ord(data):
print("False")