MySQL JSON 查询发送随机数

MySQL JSON Query sends random numbers

我正在 Python 中编写 MySQL 查询,使用 pymysql 将 JSON 数据发送到 MySQL table。当它发送数据时,会产生以下结果。

| id | data                                                                                                                                                                                                                                               |
+----+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 21 | 0x7B226775696C6473223A207B22383538393137313431303633343031353132223A207B226D656D62657273223A207B22343130373936333038323431303535373436223A207B22706F696E7473223A203137302C2022726166666C65735F776F6E223A20307D7D2C2022726166666C6573223A20307D7D7D |

我用来发送数据的代码如下:

        self.data_str = json.dumps(self.data)
        sql = "insert into jsondata ( data) values ('" + self.data_str + "') "
        mysql.exec_sql(sql)
        mysql.close_db()

exec_sql函数是:

    def exec_sql(self, sql):
        # sql is insert, delete or update statement
        cursor = self.db.cursor()
        try:
            cursor.execute(sql)
            # commit sql to mysql
            self.db.commit()
            cursor.close()
            return True
        except:
            self.db.rollback()
        return False

JSON 数据的示例行是

{"guilds": {"853317141063401512": {"members": {"410846308241055746": {"points": 250, "raffles_won": 0}}, "raffles": 0}}}

我的 SQL table 设置如下:

| Field | Type   | Null | Key | Default | Extra          |
+-------+--------+------+-----+---------+----------------+
| id    | int(6) | NO   | PRI | NULL    | auto_increment |
| data  | blob   | YES  |     | NULL    |                |
+-------+--------+------+-----+---------+----------------+

字节不是随机的。它们是 JSON 字符串中 ASCII 字节的十六进制表示。观察:

mysql> select unhex('7B226775696C6473223A207B22383538393137313431303633343031353132223A207B226D656D62657273223A207B22343130373936333038323431303535373436223A207B22706F696E7473223A203137302C2022726166666C65735F776F6E223A20307D7D2C2022726166666C6573223A20307D7D7D') as j;
+--------------------------------------------------------------------------------------------------------------------------+
| j                                                                                                                        |
+--------------------------------------------------------------------------------------------------------------------------+
| {"guilds": {"858917141063401512": {"members": {"410796308241055746": {"points": 170, "raffles_won": 0}}, "raffles": 0}}} |
+--------------------------------------------------------------------------------------------------------------------------+

您看到的是,当您将 JSON 字符串存储在二进制列 (BLOB) 中时,MySQL“忘记”它应该是文本,并且只转储查询时字节的十六进制编码。

如果要存储 JSON,则使用 the JSON data type,而不是 BLOB。