使用Python将JSON插入MySQL
我在Python中有一个JSON对象。我正在使用Python的数据库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()
相关问题:
- 如何在Postgres中使用[Insert into...select]语句插入元组,而不是[Insert into...values]方法
- Python 忽略 MySQL IntegrityError,当尝试添加重复主键时
- Python json 忽略非ascii字符 UnicodeDecodeError: 'ascii' 编解码器无法解码字节
- 使用多个SQL语句更新数据库
- 向sqlite插入JSON数据 - OperationalError: 未识别的标记 "{
- 如何让SQLAlchemy正确将unicode省略号插入MySQL表中?
- 如何将numpy中的表插入MySQL
- Python中的MySQL语句:变量不工作
9 个回答
6
为了更好地理解其他回答的内容,下面我来详细解释一下:
基本上,你需要确保两件事:
你要确保有足够的空间来存放你想要插入的数据。不同类型的数据库字段可以存放不同量的数据。你可以查看一下这个链接了解更多:MySQL 字符串数据类型。一般来说,你可能需要使用“TEXT”或“BLOB”类型。
你要确保安全地将数据传递给数据库。有些传递数据的方法可能会让数据库“误解”数据,如果数据看起来像SQL语句,数据库就会感到困惑。这也是一个安全隐患。你可以参考这个链接了解更多:SQL 注入。
解决第一个问题的方法是检查数据库是否使用了正确的字段类型。
解决第二个问题的方法是使用参数化查询(绑定查询)。比如,不要这样写:
# Simple, but naive, method.
# Notice that you are passing in 1 large argument to db.execute()
db.execute("INSERT INTO json_col VALUES (" + json_value + ")")
而是应该这样写:
# Correct method. Uses parameter/bind variables.
# Notice that you are passing in 2 arguments to db.execute()
db.execute("INSERT INTO json_col VALUES %s", json_value)
希望这些信息对你有帮助。如果有帮助,请告诉我。:-)
如果你仍然遇到问题,我们需要更仔细地检查你的语法。
8
将Python中的字典(map)直接放入MySQL的JSON字段中,最简单的方法是...
python_map = { "foo": "bar", [ "baz", "biz" ] }
sql = "INSERT INTO your_table (json_column_name) VALUES (%s)"
cursor.execute( sql, (json.dumps(python_map),) )
33
使用 json.dumps(json_value) 可以把你的 JSON 对象(也就是 Python 对象)转换成一个 JSON 字符串,这样你就可以把它放进 MySQL 的文本字段里了。