简体   繁体   中英

Query from more than one table Python Mysql Connector

I have the following sql query:

SELECT
    pc.patente,
    cs.cpc_group_codigo_cpc_group

FROM
    patente_pc pc
    ,
    patente_cpc cpc,
    cpc_subgroup cs,
    cpc_group cg

WHERE
    pc.codigo_patente_pc = cpc.patente_pc_codigo_patente_pc AND
    cpc.cpc = cs.codigo_cpc_subgroup AND
    cs.cpc_group_codigo_cpc_group = cg.codigo_cpc_group

GROUP BY    
    pc.patente, cs.cpc_group_codigo_cpc_group

I add this query to python, separating line by line the string in a tuple to not have a problem with the syntax.. and it executes correctly

but when I need to retrieve the data, I use

lista_cpcs = []
lista_patentes = []
for (pc.patente, cs.cpc_group_codigo_cpc_group) in cursor:
    lista_cpcs.append(cs.cpc_group_codigo_cpc_group)
    lista_patentes.append(pc.patente)

return [lista_cpcs, lista_patentes]

and I get the error Global name 'pc' is not defined

I get whats happening, it's interpreting pc and cs as python modules, but they are from the sql.. how to work in this? Ps: I search for python mysql connector and didn't found anything with this.

The variables in your for loop: (pc.patente, cs.cpc_group_codigo_cpc_group) are user defined; the names used do not have anything to do with the names from the query. Thus, you can call them whatever you want. You may consider using (pc__patente, cs__cpc_group_codigo_cpc_group) or something.

The problem is that the dot notation in python != the dot notation from your SQL.

Got it, sorry for the post.. Searching in https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-description.html I learned a few attributes of the cursor, and using the Eclipse debugger I saw that it comes just the name, not the table connection..so I use

for (patente, cpc_group_codigo_cpc_group) in cursor:
    lista_cpcs.append(cpc_group_codigo_cpc_group)
    lista_patentes.append(patente)

and it's working now, and thanks for the help @Scott

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM