0

我目前有一个函数,它将字典作为输入并将数据库表中的所有列作为字典返回:

import sqlite3

def get_person_dict_from_dict(self):
    database = "/Users/Mary/Documents/Database/{DB}.db".format(DB=self['db'])
    conn = sqlite3.connect(database)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    sql_command = "SELECT * FROM {dbTableIn} WHERE Identifier = '{nameIn}' AND Day = {dateIn};".format(
        dbTableIn=self['my_table'],
        dateIn=self['date'],
        nameIn=self['names'])
    c.execute(sql_command)
    r = c.fetchall()
    result = [dict(row) for row in r]
    dict_out = result[0]
    return dict_out

inputDict = {"date" : '19891229',"names" : 'Mary', "db" :'MyDatabase', "my_table" :'Measurements'}
outputDict = get_person_dict_from_dict(inputDict)

这工作正常。但是,我该如何改进它:

1)我可以包含一个额外的参数,作为可变长度的列表/元组/字典,这样我就可以只提取我感兴趣的属性,而不是所有可用的指标。例如:

attributesWanted = ['Age', 'Height']
inputDict = {attributesWanted, "date" : '19891229',"names" : 'Mary', "db" :'MyDatabase', "my_table" :'Measurements'}

然而,例如,能够灵活地使用attributesWanted = ['Age', 'Height', 'ShoeSize'] if needed.

2)能够为多个人执行此操作。例如namesWanted = ['Mary', 'Joe']

最好能够使用单个字典作为函数的输入。我尝试过包含列表和元组,但遇到了诸如

TypeError:“元组”对象不是映射

4

1 回答 1

0

我建议使用将子句解析到相关列并传递 args 的外部函数, column_type这样您就可以在值类型之间推迟另一件事是在给定函数中使用 kwargs(关键字 args)

这是一个解析参数并连接它们的简短示例。

import sqlite3

def format_arg(key, value):
    ## remove the suffix
    key_without_suffix = "_".join(key.split("_")[:-1])
    if key.endswith("str"):
        return "{key} = '{value}'".format(key=key_without_suffix, value=value)
    if key.endswith("date"):
        return "{key} = {value}".format(key=key_without_suffix, value=value)
    if key.endswith("list"):
        return "{key} IN ({value})".format(key=key_without_suffix, value=(",".join(value)))

def get_person_dict_from_dict(db, table, **kwargs):
    database = "/Users/Mary/Documents/Database/{DB}.db".format(DB=db)
    conn = sqlite3.connect(database)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    where_clause = " AND ".join([format_arg(k,v) for k,v in kwargs.items()])
    sql_command = "SELECT * FROM {table} WHERE {where};".format(
        table=table, where=where_clause)
    c.execute(sql_command)
    r = c.fetchall()
    result = [dict(row) for row in r]
    dict_out = result[0]
    return dict_out

input_dict = {"Date_date": "19891229", "names_list": ["Marry", "Anne"]}
get_person_dict_from_dict(db="MyDatabase", table="Measurements", **input_dict)
于 2019-12-24T12:51:20.140 回答