gpt4 book ai didi

python - 在 python 中使用 MysqlDb 将 null 转换为 None

转载 作者:行者123 更新时间:2023-11-30 22:25:04 25 4
gpt4 key购买 nike

下面是我的代码

import MysqlDB as mob

Mysqlconn = mdb.connect(hostname, username, password, databasename,port=3306,cursorclass=mdb.cursors.DictCursor)
Mysqlcur = self.Mysqlcon.cursor()
Mysqlcur.execute("Select * from users where date = %(date_check)s,{"date_check":current_date})
row = self.Mysqlcur.fetchall()
fileOpen = open("filename.csv","w")
for each in row:
fileOpen.write(str(each["A"])+","+str(each["B"]))

它适用于没有空值的行。当它遇到列的空值时,它会自动插入“无”而不是空值。

如何避免插入 None?

空列的数据类型可以是时间戳或字符串。

有没有人遇到过这样的问题?

最佳答案

Python 中的 SQL 连接器将始终自动将数据库中的 native 值转换为适当的 Python 类型。这不会只发生在 MySQL 上。

您面临的问题是由于您希望从程序中输出“SQLish”文本。在普通代码中,None 是一个更合适的值,也是 Python 术语中 SQL“Null”的正确表示。

然而,None 的 str 表示是“None”——如果你想要 Null,上面代码中最简单的解决方法是在你将值设置为 str 的地方写一个表达式,因此,如果值为“None”,它会得到字符串“null”。

这可以在每次调用 str 时使用三元 if 来完成:

fileOpen.write(str(each["A"] if each["A"] is not None else "null")+","+str(each["B"] if each["B"] is not None else "null"))

当然,你应该想使用字符串格式化,就是用“+”连接字符串:

fileOpen.write("{},{}".format(
each["A"] if each["A"] is not None else "null",
each["B"] if each["B"] is not None else "null",
)

或者,如果您的值永远不是空字符串或数字 0,您可以使用 or 运算符快捷方式而不是三元 if

fileOpen.write("{},{}".format(
each["A"] or "null",
each["B"] or "null"
)

关于python - 在 python 中使用 MysqlDb 将 null 转换为 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35504098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com