在Python中从数据库读取对象属性

时间:2019-01-17 12:28:06

标签: python database object

我有一个课目是

class Item: #This item is for the contents of a given site.
    def __init__(self, site, username, password):
        self.site = site #Each site should have a unique name
        self.username = username #site username/email
        self.password = password #site password

并将其保存到数据库中并且可以毫无问题地检索它,但是我随后对每个循环使用a来分别读取每个项目(这也有效),但是当我尝试访问给定的属性时,例如密码,我得到了错误:

AttributeError: 'tuple' object has no attribute 'password'

这是我读取的代码:

def read():
    mydb = mysql.connector.connect(
        host="localhost",
        user="user",
        passwd="pass",
        database="thisDb"
    )
    mycursor = mydb.cursor()

    mycursor.execute("SELECT * FROM data")

    myresult = mycursor.fetchall()
    for x in myresult:
        print(x.password)

2 个答案:

答案 0 :(得分:2)

fetchall()方法返回list中的tuples。从文档中:

  

该方法获取查询结果集的所有(或所有剩余)行   并返回一个元组列表。如果没有更多行可用   返回一个空列表。

因此在代码的这一部分:

myresult = mycursor.fetchall()
for x in myresult:
    print(x.password)

myresult是一个列表,而xtuple

MySQLCursorNamedTuple游标类,而不是使用原始游标。这样一来,您就可以使用属性查找语法访问列,而不必实例化类。

这里是记录的示例:

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(named_tuple=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe with population:")
for row in cursor:
    print("* {Name}: {Population}".format(
        Name=row.Name,
        Population=row.Population
    ))

此外,您可以尝试使用MySQLCursorDict,它将返回列名到值的映射。

然后,您可以轻松地将dict结果转换为对象的实例,例如:

myresult = dictcursor.fetchall()
for x in myresult:
    inst = Item(**x)
    print(inst.password)

或者,使用SQLAlchemy之类的ORM,听起来像它可能满足您的需求。

答案 1 :(得分:1)

我强烈建议不要使用*,而是声明各列。由于fetchall()方法返回一个元组列表。如果您知道有哪些列,您可以像这样解压结果。

for x in myresult:
    column1, column2, column3 = x