Using MysqlDb in python converts null to None

♀尐吖头ヾ 提交于 2021-01-28 22:13:50

问题


Below is my code

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"]))

It works fine for the rows which does not have null values. When it encounters a null value for a column, it automatically inserts "None" instead of null.

How do I avoid inserting None?

Datatype for null columns could be timestamp or string.

Has anybody faced such issue before?


回答1:


SQL Connectors in Python will always automatically convert from the native values in the DB to the appropriate Python type. This won't happen only with MySQL.

The problem you are facing is due to the fact that you want an "SQLish" text output out of your program. In normal code, None is a much more suitable value and the correct representation of an SQL "Null" in Python terms.

However, the str representation of None is "None" - if you want Null, the easiest work around in the code above is to write an expression on the place you cerce your values to str, so that if the value is 'None', it gets the string 'null' instead.

That can be done with ternary if inside each call to str:

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

Of course, you should want to use string formating, isnetad of concatenating strings with "+" :

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

Or, if your values are never the empty string or numeric 0, you can use the or operator shortcut instead of the ternary if

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


来源:https://stackoverflow.com/questions/35504098/using-mysqldb-in-python-converts-null-to-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!