Python / psycopg2 DONDE EN la declaración
¿Cuál es el método correcto para que la lista (countryList) esté disponible a través de %s en la instrucción SQL?
# using psycopg2
countryList=['UK','France']
sql='SELECT * from countries WHERE country IN (%s)'
data=[countryList]
cur.execute(sql,data)
Como está ahora, se equivoca después de intentar ejecutar "WHERE country in (ARRAY[...])". ¿Hay otra manera de hacer esto que no sea a través de la manipulación de cuerdas?
Gracias
34
2 answers
Para el operador IN
, desea una tupla en lugar de list, y elimine los paréntesis de la cadena SQL.
# using psycopg2
data=('UK','France')
sql='SELECT * from countries WHERE country IN %s'
cur.execute(sql,(data,))
Durante la depuración se puede comprobar que el SQL se construye correctamente con
cur.mogrify(sql, (data,))
52
Author: Bryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-23 19:59:11
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-23 19:59:11
Para explicar un poco la respuesta y abordar los parámetros con nombre, y convertir listas a tuplas:
countryList = ['UK', 'France']
sql = 'SELECT * from countries WHERE country IN %(countryList)s'
cur.execute(sql, { # You can pass a dict for named parameters rather than a tuple. Makes debugging hella easier.
'countryList': tuple(countryList), # Converts the list to a tuple.
})
13
Author: Joshua Burns,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-02 22:19:50
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-02 22:19:50