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

Using MysqlDb in python converts null to None

下面是我的代码

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" 而不是 null.

如何避免插入 None?

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

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

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

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

但是,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"
)