Domanda

Ho un oggetto JSON in Python. Sto usando Python DB-API e simplejson. Sto cercando di inserire il JSON in una tabella di MySQL.

Al momento sto ricevendo errori e credo che sia dovuto ai singoli apici '' nel JSON Oggetti.

Come posso inserire il mio JSON oggetto in MySQL con Python?

Ecco il messaggio di errore ottengo:

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

Un altro errore di riferimento

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

Questo è il link per il codice che sto usando 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()
È stato utile?

Soluzione

uso json.dumps (json_value) per convertire il vostro oggetto JSON (oggetto Python) in una stringa JSON che è possibile inserire in un campo di testo in MySQL

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

Altri suggerimenti

Per espandere sulle altre risposte:

Fondamentalmente è necessario assicurarsi di due cose:

  1. Che v'è spazio per l'intero ammontare di dati che si desidera inserire nel campo che si sta cercando di collocarlo. Diversi tipi di campo del database può andare bene diverse quantità di dati. Vedere: MySQL String Datatypes . Probabilmente si desidera il "testo" o tipi "blob".

  2. che si sta passando in modo sicuro i dati nel database. Alcuni modi di dati che passano possono causare il database per "look" i dati e sarà confondersi se gli sguardi di dati come SQL. E 'anche un rischio per la sicurezza. Vedere: SQL Injection

La soluzione per # 1 è quello di verificare che il database è stato progettato con il corretto tipo di campo.

La soluzione per 2 # è l'uso parametrizzato (legati) query. Per esempio, invece di:

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

Meglio, uso:

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

Spero che questo aiuti. Se è così, me lo faccia sapere. : -)

Se si continua ad avere un problema, allora avremo bisogno di esaminare la sintassi più da vicino.

Si dovrebbe essere in grado di inserire in una colonna di testo o blob facilmente

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

Il modo più semplice per inserire una mappa di pitone in un campo 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),) )

L'errore può essere dovuto a un overflow della dimensione del campo in cui si tenta di inserire il JSON. Senza alcun codice, è difficile per aiutarvi.

Avete premuroso un sistema di database non-SQL come CouchDB, che è un database orientato documento basandosi sul formato JSON?

È necessario ottenere uno sguardo alla stringa SQL reale, provare qualcosa di simile:

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)

immagino che si sta andando a trovare alcune citazioni randagi, staffe o parentesi in là.

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

Ecco un rapido suggerimento, se si vuole scrivere del codice in linea, diciamo per un valore piccolo JSON, senza import json. Si può sfuggire citazioni in SQL da una doppia citazione, vale a dire l'uso '' o "", per entrare ' o ".

codice Python di esempio (non testato):

q = 'INSERT INTO `table`(`db_col`) VALUES ("{k:""some data"";}")'
db_connector.execute(q)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top