我有一个 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()
有帮助吗?

解决方案

使用json.dumps(json_value)到您的JSON对象(Python对象)转换成JSON字符串,你可以在文本字段在MySQL

插入

http://docs.python.org/library/json.html

其他提示

扩展其他答案:

基本上你需要确保两件事:

  1. 您有足够的空间容纳要在尝试放置的字段中插入的全部数据。不同的数据库字段类型可以容纳不同数量的数据。看: MySQL 字符串数据类型. 。您可能需要“TEXT”或“BLOB”类型。

  2. 您正在安全地将数据传递到数据库。某些传递数据的方式可能会导致数据库“查看”数据,如果数据看起来像 SQL,数据库就会感到困惑。这也是一个安全风险。看: SQL注入

#1 的解决方案是检查数据库的设计是否具有正确的字段类型。

#2 的解决方案是使用参数化(绑定)查询。例如,而不是:

# 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)

希望这可以帮助。如果是这样,请告诉我。 :-)

如果您仍然遇到问题,那么我们需要更仔细地检查您的语法。

您应该能够插入到文本或BLOB列容易

db.execute("INSERT INTO json_col VALUES %s", json_value)

的最直接方式插入一个蟒地图到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),) )

该错误可能是由于您尝试插入您的JSON字段的大小的溢出。没有任何代码,这是很难帮助你。

你有体贴无SQL数据库系统,例如CouchDB的,这是一个文档面向数据库依靠JSON格式?

您需要获得看看实际的SQL字符串,尝试这样的事情:

sqlstr = "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 "about to execute(%s)" % sqlstr
twitdb.execute(sqlstr)

我想你会发现在那里一些流浪报价,括号或括号。

@route('/shoes', method='POST')
def createorder():
    cursor = db.cursor()
    data = request.json
    p_id = request.json['product_id']
    p_desc = request.json['product_desc']
    color = request.json['color']
    price = request.json['price']
    p_name = request.json['product_name']
    q = request.json['quantity']
    createDate = datetime.now().isoformat()
    print (createDate)
    response.content_type = 'application/json'
    print(data)
    if not data:
        abort(400, 'No data received')

    sql = "insert into productshoes (product_id, product_desc, color, price, product_name,         quantity, createDate) values ('%s', '%s','%s','%d','%s','%d', '%s')" %(p_id, p_desc, color, price, p_name, q, createDate)
    print (sql)
    try:
    # Execute dml and commit changes
        cursor.execute(sql,data)
        db.commit()
        cursor.close()        
    except:
    # Rollback changes
        db.rollback()
    return dumps(("OK"),default=json_util.default)

下面是一个简单的提示,如果你想写一些内嵌代码,说一个小的JSON值,没有import json。 可以通过一个双引号,即使用''""转义引号在SQL,进入'"

样品Python代码(未测试):

q = 'INSERT INTO `table`(`db_col`) VALUES ("{k:""some data"";}")'
db_connector.execute(q)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top