質問

私はPythonにJSONオブジェクトを持っています。 Python DB-APIとSimpleJsonを使用しています。 JSONをMySQLテーブルに挿入しようとしています。

現時点ではエラーが発生しており、JSONオブジェクトの単一の引用符が原因だと思います。

これが私が得るエラーメッセージです:

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)を使用して、mysqlのテキストフィールドに挿入できるJSON文字列にJSONオブジェクト(Pythonオブジェクト)を変換します

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

他のヒント

他の答えを拡張するには:

基本的に、2つのことを確認する必要があります。

  1. あなたがそれを配置しようとしているフィールドに挿入したい完全なデータのためのスペースがあること。異なるデータベースフィールドタイプは、さまざまな量のデータに適合できます。見る: mysql文字列データ型. 。おそらく「テキスト」または「ブロブ」タイプが必要です。

  2. データをデータベースに安全に渡していること。データを渡すいくつかの方法により、データベースがデータを「調べる」ことができ、データがSQLのように見えると混乱します。また、セキュリティリスクです。見る: SQLインジェクション

#1のソリューションは、データベースが正しいフィールドタイプで設計されていることを確認することです。

#2のソリューションは、Parameterized(Bound)クエリの使用です。たとえば、:の代わりに

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

お役に立てれば。もしそうなら、私に知らせてください。 :-)

まだ問題が発生している場合は、構文をより詳細に調べる必要があります。

intyoをテキストまたはブロブ列を簡単に挿入できるはずです

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

pythonマップを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を挿入しようとするフィールドのサイズのオーバーフローによる可能性があります。コードがなければ、あなたを助けるのは難しいです。

JSON形式に依存するドキュメント指向のデータベースであるCouchDBなどのNO-SQLデータベースシステムを思い浮かべますか?

実際の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