将pymysql结果转换为对象

问题描述 投票:0回答:2

我从PHP来到Python,所以我对以前在PHP中所做的某些事情感到困惑。例如,我得到了Database_object类,它具有一些通用的数据库方法,例如:

class DatabaseObject {

protected static $table_name;
protected static $db_fields;

public static function find_all() {
    return self::find_by_query("SELECT * FROM ".static::$table_name);
}

...
private static function instantiate($record) {
    $object = new self;
    foreach($record as $attribute=>$value) {
        if($object->has_attribute($attribute)) {
            $object->$attribute = $value;
        }
    }
    return $object;
}
}

以及一些子类,例如:

class User extends DatabaseObject {


protected static $table_name = "users";
protected static $db_fields = array('id', 'gid', 'username', 'hashed_password', 'first_name', 'last_name', 'e_mail', 'phone_number', 'position', 'last_login', 'comment', 'supplier_id');

我对静态实现有一些疑问,但是现在的话题是如何在Python中制作此instantiate方法?我有这样的方法:

   def FindAll(self):
        query = 'SELECT * FROM ' + self._TableName
        try:
            self.cur.execute(query)
        except(ValueError):
            print("Error " + ValueError)
        else:
            return self.cur.fetchall() 

但是这个返回数组,我想像在PHP的实例化方法中那样使它们成为对象。例如,如果我为用户类调用FindAll。我想获得一系列用户,然后像这样使用它们:

   for user in users:
       print("Username: {}, Name: {} {}".format(user.username, user.first_name, user.second_name)

而不是:

print("Username: {}, Name: {} {}".format(user[1], user[3], user[4]))

像现在一样。

python arrays object methods pymysql
2个回答
0
投票

使用pymysql.cursors.DictCursor,它将返回以字典表示的行,这些行将列名映射到值。

>>> from pymysql.cursors import DictCursor
>>> with pymysql.connect(db='foo', cursorclass=DictCursor) as cursor:
...     print cursor
... 

信用:Mark Amery


0
投票

我对您的主题的理解是,您想获取一个python dict对象而不是list对象。

您可以使用与所需内容相似的方式浏览字典。例如:

people = {"John": "Doe", "Eddy": "Malou"}

您可以从这样的名字访问名字

people["John"] # will return Doe
people["Eddy"] # will return Malou

使用pymysql,默认情况下,使用select查询时,您将获得结果列表。

如果要获取字典,则需要指定要获取标头。您可以按照以下步骤进行操作:

results = {}
headers = [row[0] for row in cursor.description]
index = 0

"""
Browse a dict to return a dict with the following format:
results = {
    header1: [result_list1],
    header2: [result_list2],
    header3: [result_list3]
}
"""

for header in headers:
    result_list = []

    for element in result:
        result_list.append(element[index])

    results[header] = result_list
    index +=1

return results
© www.soinside.com 2019 - 2024. All rights reserved.