gustavo serna gustavo serna - 4 months ago 40
MySQL Question

Python MySql make array of a Query

I have a MySql query, everything works fine, but I want to make an array of each row to be used out of the query

Here is my code:

db = MySQLdb.connect(host="127.0.0.1", user="root", passwd="", db="seliso")

cursor = db.cursor()

cursor.execute("SELECT * FROM usuarios WHERE contador = " + "'" + userContador + "'")

results = cursor.fetchall()

for row in results:
rfc = row[1]
clave = row[2]


Example of I want to do:

db = MySQLdb.connect(host="127.0.0.1", user="root", passwd="", db="seliso")

cursor = db.cursor()

cursor.execute("SELECT * FROM usuarios WHERE contador = " + "'" + userContador + "'")

results = cursor.fetchall()

for row in results:
rfc = row[1]
clave = row[2]

$arrayRFC = ["rfc1", "rfc2", "rfc3"]
$arrayClave = ["clave1", "clave2", "clave3"]


How can this be acheived?

Thanks in advance.

Answer

You can get that with:

for i in zip(*results):
    print(list(i))

Further, you should not use string concatenation like that for reasons of SQL injection. Instead do:

cursor.execute("SELECT * FROM usuarios WHERE contador = %s",(userContador,))

Where %s is the parameter style per: http://mysql-python.sourceforge.net/MySQLdb.html