[Python][MySQL]Python stores JSON data in text form in the Text type field of MySQL

1. Cause

I'm making an automatic check-in thing. Log in to get a series of information about that platform. I don't want to specifically modify or add database fields for storage, so I plan to directly save the returned JSON data into a MySQL field.

The content must not be placed directly, consider the problem of data injection, right, it is easy to go wrong, so I intend to convert the JSON data into a base64-encoded format.

First write a special encoding tool function

def Base64_encode(s):
    res = str(base64.b64encode(s.encode("utf-8"))).replace("b'","")[:-1]
    return  res

str(base64.b64encode(s.encode("utf-8")))What I get is the text of b'xxx', I don't want to replace it b'with the following , and then the database operation is as follows:'

try:
        cur, db = db_connect()
    except:
        return {"code": 33060, "msg": "连接数据库失败", "data": {}}
    try:
        sql  = "update t_info set `token`='%s',`uid`='%s',`planids`='%s',`moguNo`='%s' where `gaccount`='%s'"%(Base64_encode(json.dumps(user_token)),user_id,Base64_encode(json.dumps(plan_ids)) ,moguNo,tel)
        print("\n",sql,"\n")
        result = cur.execute(sql)
    except Exception as e:
        print(e)
        return {"code":-1,"msg":"发生了错误"}

Pay attention to the length problem! Varchar (255) is easy to hold, so if it is too long, use the text type to hold it.

Then just decode

def Base64_decode(s):
    return base64.b64decode(s).decode("utf-8")

in conclusion:

def Base64_encode(s):
    res = str(base64.b64encode(s.encode("utf-8"))).replace("b'","")[:-1]
    return  res

def Base64_decode(s):
    return base64.b64decode(s).decode("utf-8")

Guess you like

Origin blog.csdn.net/ks2686/article/details/130437776