我想在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'];
?>
感谢。
答案 0 :(得分:5)
pip install mysql-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
答案 1 :(得分:5)
在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)
答案 2 :(得分: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()
答案 3 :(得分:1)
您可以使用以下( 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'])
答案 4 :(得分:0)
尝试:
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” 返回一个列表而不是一个数组,因此您可以使用其键名引用数据,在您的情况下使用姓氏。