1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you so much, you are the best! :)
Cheers, mate. Happy coding to you :-)
but how can I use it out of "for:"
bro sorry, that isn't what I need. I need to use de "row" array out of "for:"
mmm.. here is a php example: <?php $r=mysql_query("select * from clientes"); while($row=mysql_fetch_array($r)){ $cls[]=$row; } print(json_encode($cls)); mysql_close($con); ?>
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.