Python equivalent for PHP mysql_fetch_array

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

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.

+4
source share
5 answers
  • Install MySQLdb (drivers for MySQL for Python). Type pip install mysql-python
  • Read on the Python API , which is the standard way to access Python databases.

Then try the following:

 >>> import MySQLdb >>> connection = MySQLdb.connect(database='test') >>> cursor = connection.cursor() >>> cursor.execute('SELECT * FROM users WHERE firstname = %s',('somename',)) >>> results = cursor.fetchall() >>> for i in results: print i 
+5
source

In Python you have dictionary=True , I tested in python3. This returns a directory that is very similar to an 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) 
+5
source

I would use SQLAlchemy . Something like this will do the trick:

  engine = create_engine ('mysql: // username: password@host : port / database')
 connection = engine.connect ()
 result = connection.execute ("select username from users")
 for row in result:
     print "username:", row ['username']
 connection.close ()
+1
source

You can use this:

 import mysql.connector cursor = db.cursor(dictionary=True) cursor.execute("SELECT * FROM table") for row in cursor: print(row['column']) 
+1
source

Try:

 import MySQLdb connection = MySQLdb.connect(host="localhost", # your host user="root", # username passwd="password", # password db="frateData") # name of the database) cursor = connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM users WHERE firstname = %s',['namehere']) data = cursor.fetchall() print data['lastname'] 

Please note that starting the cursor by passing the following parameter: "MySQLdb.cursors.DictCursor" returns a list instead of an array, so you can refer to the data with their key name, which in your case is the name.

0
source

All Articles