8000 Fix loading json data (#490) · codepongo/PyMySQL@95f5526 · GitHub
[go: up one dir, main page]

Skip to content

Commit 95f5526

Browse files
authored
Fix loading json data (PyMySQL#490)
1 parent dadd392 commit 95f5526

File tree

2 files changed

+35
-7
lines changed

2 files changed

+35
-7
lines changed

pymysql/converters.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,12 @@ def convert_set(s):
333333
return set(s.split(","))
334334

335335

336+
def convert_json(b):
337+
# JSON is returned as binary data.
338+
# Decode with utf-8 regardless connection encoding.
339+
return b.decode('utf-8')
340+
341+
336342
def through(x):
337343
return x
338344

@@ -410,6 +416,7 @@ def convert_characters(connection, field, data):
410416
FIELD_TYPE.VARCHAR: through,
411417
FIELD_TYPE.DECIMAL: Decimal,
412418
FIELD_TYPE.NEWDECIMAL: Decimal,
419+
FIELD_TYPE.JSON: convert_json,
413420
}
414421

415422

pymysql/tests/test_basic.py

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
1-
import pymysql.cursors
2-
3-
from pymysql.tests import base
4-
from pymysql import util
5-
from pymysql.err import ProgrammingError
6-
7-
import time
1+
# coding: utf-8
82
import datetime
3+
import json
4+
import time
95
import warnings
106

117
from unittest2 import SkipTest
128

9+
from pymysql import util
10+
import pymysql.cursors
11+
from pymysql.tests import base
12+
from pymysql.err import ProgrammingError
13+
1314

1415
__all__ = ["TestConversion", "TestCursor", "TestBulkInserts"]
1516

@@ -238,6 +239,26 @@ def test_single_tuple(self):
238239
self.assertEqual([(1,)], list(c.fetchall()))
239240
c.close()
240241

242+
def test_json(self):
243+
args = self.databases[0].copy()
244+
args["charset"] = "utf8mb4"
245+
conn = pymysql.connect(**args)
246+
if not self.mysql_server_is(conn, (5, 7, 0)):
247+
raise SkipTest("JSON type is not supported on MySQL <= 5.6")
248+
249+
self.safe_create_table(conn, "test_json", """\
250+
create table test_json (
251+
id int not null,
252+
json JSON not null,
253+
primary key (id)
254+
);""")
255+
cur = conn.cursor()
256+
json_str = u'{"hello": "こんにちは"}'
257+
cur.execute("INSERT INTO test_json (id, `json`) values (42, %s)", (json_str,))
258+
cur.execute("SELECT `json` from `test_json` WHERE `id`=42")
259+
res = cur.fetchone()[0]
260+
self.assertEqual(json.loads(res), json.loads(json_str))
261+
241262

242263
class TestBulkInserts(base.PyMySQLTestCase):
243264

0 commit comments

Comments
 (0)
0