Are you using PyMySQL? Eh? I'm using ORM, so why not use that?
Well, ORM can be annoying with ORM, isn't it? Isn't it easy to write SQL in chok?
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
# Create a new record
sql = "SELECT * from users where first_name = 'bob'"
cursor.execute(sql, connection)
And.
cursorclass = pymysql.cursors.DictCursor
is useful.
{'name': 'bob', 'id': 1}
Because it returns a Dict like this.
But this. This is what happens when there is NULL.
[{'first_name': 'bob', 'last_name': 'smith', 'id': 1, 'phone_num': None},
{'first_name': 'bob', 'last_name': 'jones', 'id': 2, 'phone_num': None}]
Please return " NULL "
instead of None
.
When it is NULL
, you can return"NULL"
and it is in the specification.
So why not replace the return value with something like for i in ...:
?
What is DictCursor doing?
class DictCursor(DictCursorMixin, Cursor):
"""A cursor which returns results as a dictionary"""
Nothing. What about DictCursorMixin?
class DictCursorMixin(object):
# You can override this to use OrderedDict or other dict-like types.
dict_type = dict
"Override with Dict-like!"
Test is also doing it, so it's okay to do it
d = {"foo": "bar", "baz": None}
assert d["baz"] == "NULL"
Should I make a Dict like this?
class MyDict(dict):
def __init__(self):
#Do something
Anyway, it looks like this? Dunder I want to play around with it, but what kind of implementation is dict?
Look here ... I can't read it because the source is C. (Though you can read it if you are a stubborn person ...)
Since the source says "Please put OrderedDict", the source of OrderedDict is ...
Is it okay to use OrderedDict?
class OrderedDict(dict):
def __init__(self, other=(), /, **kwds):
# (Abbreviation)
self.__update(other, **kwds)
update is this?, but I'm not sure, so I will implement it appropriately.
class MyDict(dict):
def __init__(self, other=None):
super().__init__()
self._update(other)
def _update(self, other=None):
if other is not None:
for h, i in other:
if i:
self[h] = i
else:
self[h] = "NULL"
class MyDictCursor(cursors.DictCursor):
dict_type = MyDict
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=MyDict)
When this happens.
[{'first_name': 'bob', 'last_name': 'smith', 'id': 1, 'phone_num': "NULL"},
{'first_name': 'bob', 'last_name': 'jones', 'id': 2, 'phone_num': "NULL"}]
Recommended Posts