使用 Python 将 JSON 插入 MySQL
我有一个 Python 中的 JSON 对象。我正在使用 Python DB-API 和 SimpleJson。我正在尝试将 json 插入 MySQL 表中。
目前出现错误,我相信这是由于 JSON 对象中的单引号 '' 造成的。
如何使用 Python 将 JSON 对象插入 MySQL?
这是我收到的错误消息:
error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7ff68f91d7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for
the right syntax to use near ''favorited': '0',
'in_reply_to_user_id': '52063869', 'contributors':
'NULL', 'tr' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-py2.5.egg/
twitstream/twitasync.py|found_terminator|55] [twitter.py|callback|26]
[build/bdist.linux-x86_64/egg/MySQLdb/cursors.py|execute|166]
[build/bdist.linux-x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
另一个错误供参考
error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7feb9d52b7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right
syntax to use near 'RT @tweetmeme The Best BlackBerry Pearl
Cell Phone Covers http://bit.ly/9WtwUO''' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-
py2.5.egg/twitstream/twitasync.py|found_terminator|55]
[twitter.py|callback|28] [build/bdist.linux-
x86_64/egg/MySQLdb/cursors.py|execute|166] [build/bdist.linux-
x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
这是我正在使用的代码的链接 http://pastebin。 com/q5QSfYLa
#!/usr/bin/env python
try:
import json as simplejson
except ImportError:
import simplejson
import twitstream
import MySQLdb
USER = ''
PASS = ''
USAGE = """%prog"""
conn = MySQLdb.connect(host = "",
user = "",
passwd = "",
db = "")
# Define a function/callable to be called on every status:
def callback(status):
twitdb = conn.cursor ()
twitdb.execute ("INSERT INTO tweets_unprocessed (text, created_at, twitter_id, user_id, user_screen_name, json) VALUES (%s,%s,%s,%s,%s,%s)",(status.get('text'), status.get('created_at'), status.get('id'), status.get('user', {}).get('id'), status.get('user', {}).get('screen_name'), status))
# print status
#print "%s:\t%s\n" % (status.get('user', {}).get('screen_name'), status.get('text'))
if __name__ == '__main__':
# Call a specific API method from the twitstream module:
# stream = twitstream.spritzer(USER, PASS, callback)
twitstream.parser.usage = USAGE
(options, args) = twitstream.parser.parse_args()
if len(args) < 1:
args = ['Blackberry']
stream = twitstream.track(USER, PASS, callback, args, options.debug, engine=options.engine)
# Loop forever on the streaming call:
stream.run()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
使用 json.dumps(json_value) 将 json 对象(python 对象)转换为 json 字符串,您可以将其插入到 mysql 的文本字段中
http://docs.python.org/library/json.html
use json.dumps(json_value) to convert your json object(python object) in a json string that you can insert in a text field in mysql
http://docs.python.org/library/json.html
将 python 映射插入 MySQL JSON 字段的最直接方法...
The most straightforward way to insert a python map into a MySQL JSON field...
要扩展其他答案:
基本上,您需要确保两件事:
您有足够的空间容纳要在尝试放置的字段中插入的全部数据。不同的数据库字段类型可以容纳不同数量的数据。
请参阅:MySQL 字符串数据类型。您可能需要“TEXT”或“BLOB”类型。
您正在安全地将数据传递到数据库。某些传递数据的方式可能会导致数据库“查看”数据,如果数据看起来像 SQL,数据库就会感到困惑。这也是一个安全风险。请参阅:SQL 注入
#1 的解决方案是检查数据库是否设计有正确的字段类型。
#2 的解决方案是使用参数化(绑定)查询。例如,不要使用:
更好,而是使用:
希望这会有所帮助。如果是这样,请告诉我。 :-)
如果您仍然遇到问题,那么我们需要更仔细地检查您的语法。
To expand on the other answers:
Basically you need make sure of two things:
That you have room for the full amount of data that you want to insert in the field that you are trying to place it. Different database field types can fit different amounts of data.
See: MySQL String Datatypes. You probably want the "TEXT" or "BLOB" types.
That you are safely passing the data to database. Some ways of passing data can cause the database to "look" at the data and it will get confused if the data looks like SQL. It's also a security risk. See: SQL Injection
The solution for #1 is to check that the database is designed with correct field type.
The solution for #2 is use parameterized (bound) queries. For instance, instead of:
Better, use:
Hope this helps. If so, let me know. :-)
If you are still having a problem, then we will need to examine your syntax more closely.
您应该能够轻松插入文本或 blob 列
You should be able to insert intyo a text or blob column easily
您需要查看实际的 SQL 字符串,尝试这样的操作:
我想您会在其中找到一些杂散的引号、方括号或圆括号。
You need to get a look at the actual SQL string, try something like this:
I imagine you are going to find some stray quotes, brackets or parenthesis in there.
一个示例,如何使用
Python
将JSON
文件添加到MySQL
中。这意味着需要将JSON
文件转换为sql insert
,如果有多个JSON
对象那么最好只有一个调用INSERT
比多次调用,即对每个对象调用函数INSERT INTO
。输出:
One example, how add a
JSON
file intoMySQL
usingPython
. This means that it is necessary to convert theJSON
file tosql insert
, if there are severalJSON
objects then it is better to have only one callINSERT
than multiple calls, ie for each object to call the functionINSERT INTO
.output:
该错误可能是由于您尝试插入 json 的字段大小溢出所致。没有任何代码,很难帮助你。
您是否考虑过像 couchdb 这样的 no-sql 数据库系统,它是一个依赖 json 格式的面向文档的数据库?
The error may be due to an overflow of the size of the field in which you try to insert your json. Without any code, it is hard to help you.
Have you considerate a no-sql database system such as couchdb, which is a document oriented database relying on json format?
如果您想编写一些内联代码,例如小 json 值,而不使用
import json
,这里有一个快速提示。您可以在 SQL 中通过双引号转义引号,即使用
''
或""
输入'
或"
示例Python代码(未测试):
Here's a quick tip, if you want to write some inline code, say for a small json value, without
import json
.You can escape quotes in SQL by a double quoting, i.e. use
''
or""
, to enter'
or"
.Sample Python code (not tested):