问题
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