将pymysql结果转换为对象

时间:2020-01-06 07:24:44

标签: python arrays object methods pymysql

我从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]))

像现在这样。

2 个答案:

答案 0 :(得分:0)

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

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

信用:Mark Amery

答案 1 :(得分: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

然后,您可以按以下方式浏览结果,将“ headerX”替换为列/标题名称:

for result in results:
    print(f"My first header {result['header1']}, my second header {result['header2']} and my last header {result['header3']}.")