[PYTHON] How to make an arbitrary DictCursor with PyMySQL and not return None when NULL

Preface

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?

With PyMySQL

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 ...:?

Source code

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

Then

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.

Summary

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

How to make an arbitrary DictCursor with PyMySQL and not return None when NULL
How to extract null values and non-null values with pandas
How to make an HTTPS server with Go / Gin
How to not load images when using PhantomJS with Selenium
How to do Bulk Update with PyMySQL and notes [Python]
Precautions when inputting from CSV with Python and outputting to json to make it an exe
How to deal with "fatal: destination path''already exists and is not an empty directory." When trying to clone on Git hub
How to not escape Japanese when dealing with json in python
How to deal with errors when installing whitenoise and deploying to Heroku
How to create a heatmap with an arbitrary domain in Python
How to deal with errors when installing Python and pip with choco
[Introduction to Python] How to judge authenticity with if statement (True and None)
[AWS] How to deal with WordPress "An error occurred when cropping an image."
Fractal to make and play with Python
Python + chatwork + google extension = How to make an easy and funny chat BOT
How to make an embedded Linux device driver (11)
How to make an embedded Linux device driver (8)
How to make an embedded Linux device driver (1)
How to make an embedded Linux device driver (4)
How to delete log with Docker, not to collect log
How to add arbitrary headers to response with FastAPI
How to make a dictionary with a hierarchical structure.
How to make an embedded Linux device driver (7)
How to make an embedded Linux device driver (2)
How to crop an image with Python + OpenCV
How to make an embedded Linux device driver (3)
How to deal with SessionNotCreatedException when using Selenium
How to read an array with Python's ConfigParser
[Blender x Python] How to make an animation
How to make an embedded Linux device driver (6)
How to make an embedded Linux device driver (5)
How to make an embedded Linux device driver (10)
How to make Linux compatible with Japanese keyboard
How to make an embedded Linux device driver (9)
How to return multiple indexes with index method
How to pass args or environment variables with Makefile and make command on #Linux
[Linux] How to display CPU usage, display header, and not display grep process with ps command
How to change the behavior when loading / dumping yaml with PyYAML and its details
[Learning memo] How to make an application with Django ~ Until Hello World is displayed ~
[Learning memo] How to make an application with Django ~ From virtual environment to pushing to github ~
Explain in detail how to make sounds with python
How to deal with Django's Template Does Not Exist
How to make a shooting game with toio (Part 1)
How to share folders with Docker and Windows with tensorflow
How to access with cache when reading_json in pandas
How to loop and play gif video with openCV
How to make an embedded Linux device driver (12) (Complete)
How to use Decorator in Django and how to make it
I tried to make an OCR application with PySimpleGUI
[How to!] Learn and play Super Mario with Tensorflow !!
[Raspberry Pi] How to continuously monitor directories and run arbitrary shells with hooks for changes