我无法将此查询插入到mysql中。我做了一个json.dump()。我试过文字和blob。我尝试打开和关闭引号。
INSERT INTO mytable (campaign_object)
VALUES ( {"cpa_type": "null", "device_tablets": "True",
"language": "all", "end_date": null, "bid": "1", "budget": "1", "goal_type": "ctr",
"frequency": "null", "location": "all", "device_mobile": "True", "device_desktop":
"True", "impressions": "null", "campaign_name": "1", "start_date": "2012-09-14",
"insert_date": "2012-09-13 23:00:1347548413"})
所以......我不得不想象MyhSQL可以处理json。我真的很想要泡菜。
答案 0 :(得分:2)
始终使用参数化查询。
value = '''{"cpa_type": "null", "...0:1347548413"}'''
cursor.execute("INSERT INTO mytable (campaign_object) VALUES (%s)", (value,))
这样你就可以避免需要转义json,并且可以安全地禁止SQL注入。
答案 1 :(得分:1)
取决于你的意思。
MySQL不了解JSON作为数据类型。但是您可以将JSON表达式存储为字符串。
我假设列campaign_object
被声明为字符串,如下所示:
CREATE TABLE mytable (
campaign_object NVARCHAR(8000)
);
在这种情况下,您必须将整个JSON字符串括在一个引号中,如下所示:
INSERT INTO mytable (campaign_object)
VALUES ( '{"cpa_type": "null", "device_tablets": "True",
"language": "all", "end_date": null, "bid": "1", "budget": "1", "goal_type": "ctr",
"frequency": "null", "location": "all", "device_mobile": "True", "device_desktop":
"True", "impressions": "null", "campaign_name": "1", "start_date": "2012-09-14",
"insert_date": "2012-09-13 23:00:1347548413"}')
否则,MySQL会抱怨一条神秘的消息,因为它试图将原始JSON解释为SQL。当我尝试使用表mytable
的定义在SQL Fiddle中执行您的示例时,我看到了以下错误:
架构创建失败:列数与第1行的值计数不匹配: