Python中与PHP的mysql_fetch_array函数相当的函数是什么?

8
我希望能在MySQL中获取一个数组。请问有人可以告诉我如何使用MySQLdb以Python编写代码实现吗?
例如,我希望在Python中进行以下操作:
<?php

  require_once('Config.php'); 

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

?>

谢谢。
5个回答

15

在Python中,你可以使用dictionary=True参数。我已经在Python3中测试过了。这将返回一个非常类似于PHP中的关联数组的字典。

例如:

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)

https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html - Jingshao Chen

6
您可以使用此选项(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'])

5
  1. 安装MySQLdb (Python的MySQL驱动程序)。输入 pip install mysql-python
  2. 学习Python DB API,这是Python中访问数据库的标准方式。

然后尝试以下操作:

>>> 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

2
令人担忧的是,这是唯一带有某种形式的SQL转义的答案。 - tadman
谢谢你的帮助!我只有一个问题。当我使用它时,数据以这种格式返回:(('dave',), ('jake',))。我该如何编辑此数据的格式,使其像这样('dave','jake')。我正在循环遍历返回的数据并将每个用作变量。这将更容易地满足我的需求。再次感谢。 - Austin K
13
names = [i[0] for i in cursor.fetchall()] 的意思是将从 cursor 中获取的所有数据的第一个元素取出来,存储在 names 列表中。 - Burhan Khalid

1

尝试:

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']

请注意,通过传递以下参数来初始化光标:"MySQLdb.cursors.DictCursor",将返回一个列表而不是数组,因此您可以使用它们的键名引用数据,在您的情况下是lastname。

1
我会使用SQLAlchemy。类似这样的代码可以解决问题:
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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接