python sqlite数据库操作如何返回字典

本文介绍如何在Python中使用SQLite返回字典格式的数据记录,并提供插入和更新SQL语句的生成方法。

python在使用sqlite时返回单个/多个记录时的是行信息,而我们希望能够返回字典信息。如下

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

def dic2InsertSql(dic, tblName):
    sql_key = ', '.join(dic.keys())
    sql_val = ''
    for key in dic:
        if type(dic[key]) is str:
            sql_val = sql_val + '\'' + dic[key] + '\','
        else:
            sql_val = sql_val + str(dic[key]) + ' ,'

    # 移除 sql_val最后一个 ','
    return "insert into {} ({}) values ({}) ".format(tblName, sql_key, sql_val[:-1])


# 调用者需要自己补充 where之后的条件语句
def dic2UpdateSql(dic, tblName):
    sql_key = ''
    for key in dic:
        if type(dic[key]) is str:
            sql_key = sql_key + key + ' = \'' + dic[key] + '\','
        else:
            sql_key = sql_key + key + ' = ' + str(dic[key]) + ' ,'

    # 移除 sql_key 最后一个 ','
    return "update {} set {} where  ".format(tblName, sql_key[:-1])

class SqliteBase:
    def __init__(self, dbname):
        self.conn = sqlite3.connect(dbname, check_same_thread=False)

        # 设置返回的数据库信息中携带 表字段名

        # dict_factory 一定要设置为静态函数,否则会导致变量引用计数多+1,
        # 最后导致局部变量永远无法删除,这个bug没找到具体原因
        self.conn.row_factory = dict_factory
       
    def exec(self, sql):
        """
            执行sql
            返回错误
        :param sql:
        :return:
        """
        ret = True
        cursor = self.conn.cursor()
        try:
            cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            log.logger.warning('sql {} , error: {}'.format(sql, e))
            ret = False
        finally:
            pass
        return ret
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

睡在床板下_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值