2012-01-08 12 views
9

voglio fare un Python query MySQL come ad esempio:MySQL Python COME jolly

cursor = connection.cursor() 
sql = "select text \ 
     from steps \ 
     where text like '%start%'" 
cursor.execute(sql) 

Ma l'% non è visto come un jolly, è in attesa di una variabile, immagino. Viene visualizzato un messaggio di errore:

TypeError: not enough arguments for format string 

Nulla sembra funzionare. Sarebbe anche bello se potessi usare una variabile invece di '% start%'

risposta

16

Presumo che tu stia usando python db-api.

È possibile provare a sfuggire a % come %%.

Per quanto riguarda il passaggio dei parametri v'è un certo numero di modi, ad esempio:

cursor = connection.cursor() 
sql = """select text 
    from steps 
    where text like %s""" 
cursor.execute(sql, (('%' + 'start' + '%',)) 

Potete vedere esempi di altri modi di parametro che passa on this blog nella sezione "Interfaccia modułu". Non tutti funzionano con tutti i connettori.

+1

Escaping con %% funziona, grazie :) L'uso di stringhe letterali ha dato lo stesso errore. – user984003

+0

@ user984003 strano, ma non riesco nemmeno a testarlo in questo momento. lieto mi ha aiutato comunque. – soulcheck

+0

@soulcheck: la sintassi delle stringhe non ha nulla a che fare con l'interpretazione di '%' (a differenza di come Bourne Shell o Ruby interpretano '$', ad esempio). Quindi '" ""% start% "" "' è esattamente come '"% start% "', che è uguale a ''% start%'' e 'r '% start%'', ecc. –

Problemi correlati