Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of PHP mysql_fetch_array

I would like to fetch an array in MySQL. Can someone please tell me how to use Python using MySQLdb to do so?

For example, this is what I would like to do in Python:

<?php

  require_once('Config.php'); 

  $q = mysql_query("SELECT * FROM users WHERE firstname = 'namehere'");
  $data = mysql_fetch_array($q);
  echo $data['lastname'];

?>

Thanks.

like image 422
Austin K Avatar asked Jul 19 '12 16:07

Austin K


2 Answers

In python you have dictionary=True, I have tested in python3. This returns directory which is much similar to associative array in php. eg.

import mysql.connector
cnx = mysql.connector.connect(user='root', password='',host='127.0.0.1',database='test1')
cursor = cnx.cursor(dictionary=True)
sql= ("SELECT * FROM `users` WHERE id>0")
cursor.execute(sql)
results = cursor.fetchall()
print(results)
like image 182
Anup_Tripathi Avatar answered Oct 09 '22 15:10

Anup_Tripathi


You can use this (dictionary=True):

import mysql.connector

db = mysql.connector.connect(user='root', password='',host='127.0.0.1', database='test1')

cursor = db.cursor(dictionary=True)
cursor.execute("SELECT * FROM table")

for row in cursor:
    print(row['column'])
like image 23
Daniel Avatar answered Oct 09 '22 15:10

Daniel