21

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()
4

9 に答える 9

26

json.dumps(json_value) を使用して、json オブジェクト (python オブジェクト) を mysql のテキスト フィールドに挿入できる json 文字列に変換します。

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

于 2010-11-30T17:56:24.417 に答える
6

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

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

  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)

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

それでも問題が解決しない場合は、構文をさらに詳しく調べる必要があります。

于 2010-11-23T02:04:09.767 に答える
2

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

db.execute("INSERT INTO json_col VALUES %s", json_value)
于 2010-11-23T00:09:12.710 に答える
1

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

そこには、引用符、括弧、または括弧がいくつかあると思います。

于 2010-11-30T15:18:20.577 に答える
1

一例として、 usingにJSONファイルを追加する方法。これは、ファイルをに変換する必要があることを意味します。複数のオブジェクトがある場合は、複数回呼び出すよりも 1 回だけ呼び出す方がよいでしょう。つまり、オブジェクトごとに関数を呼び出します。MySQLPythonJSONsql insertJSONINSERTINSERT INTO

# import Python's JSON lib
import json

# use JSON loads to create a list of records
test_json = json.loads('''
[
    {
    "COL_ID": "id1",
    "COL_INT_VAULE": 7,
    "COL_BOOL_VALUE": true,
    "COL_FLOAT_VALUE": 3.14159,
    "COL_STRING_VAULE": "stackoverflow answer"
    },
    {
    "COL_ID": "id2",
    "COL_INT_VAULE": 10,
    "COL_BOOL_VALUE": false,
    "COL_FLOAT_VALUE": 2.71828,
    "COL_STRING_VAULE": "http://stackoverflow.com/"
    },
    {
    "COL_ID": "id3",
    "COL_INT_VAULE": 2020,
    "COL_BOOL_VALUE": true,
    "COL_FLOAT_VALUE": 1.41421,
    "COL_STRING_VAULE": "GIRL: Do you drink? PROGRAMMER: No. GIRL: Have Girlfriend? PROGRAMMER: No. GIRL: Then how do you enjoy life? PROGRAMMER: I am Programmer"
    }
]
''')

# create a nested list of the records' values
values = [list(x.values()) for x in test_json]
# print(values)

# get the column names
columns = [list(x.keys()) for x in test_json][0]

# value string for the SQL string
values_str = ""

# enumerate over the records' values
for i, record in enumerate(values):

    # declare empty list for values
    val_list = []
   
    # append each value to a new list of values
    for v, val in enumerate(record):
        if type(val) == str:
            val = "'{}'".format(val.replace("'", "''"))
        val_list += [ str(val) ]

    # put parenthesis around each record string
    values_str += "(" + ', '.join( val_list ) + "),\n"

# remove the last comma and end SQL with a semicolon
values_str = values_str[:-2] + ";"

# concatenate the SQL string
table_name = "json_data"
sql_string = "INSERT INTO %s (%s)\nVALUES\n%s" % (
    table_name,
    ', '.join(columns),
    values_str
)

print("\nSQL string:\n\n")
print(sql_string)

出力:


SQL string:


INSERT INTO json_data (COL_ID, COL_INT_VAULE, COL_BOOL_VALUE, COL_FLOAT_VALUE, COL_STRING_VAULE)
VALUES
('id1', 7, True, 3.14159, 'stackoverflow answer'),
('id2', 10, False, 2.71828, 'http://stackoverflow.com/'),
('id3', 2020, True, 1.41421, 'GIRL: Do you drink? PROGRAMMER: No. GIRL: Have Girlfriend? PROGRAMMER: No. GIRL: Then how do you enjoy life? PROGRAMMER: I am Programmer.');
于 2020-10-07T05:30:34.203 に答える
1
@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)
于 2014-12-08T10:03:52.777 に答える
0

このエラーは、json を挿入しようとしたフィールドのサイズのオーバーフローが原因である可能性があります。コードがなければ、あなたを助けるのは難しいです.

json 形式に依存するドキュメント指向データベースである、couchdb などの SQL を使用しないデータベース システムを検討しましたか?

于 2010-11-22T23:12:03.743 に答える