当前位置: 移动技术网 > IT编程>脚本编程>Python > Python将Sqlite3查询结果保存为字典形式

Python将Sqlite3查询结果保存为字典形式

2020年04月27日  | 移动技术网IT编程  | 我要评论

画笔工具下载,鬼故事笑话,大蒜 地沟油

import sqlite3
import os

class dboperate:

    def __init__(self,dbpath=os.path.join(os.getcwd(),"db")):
        self.dbpath=dbpath
        self.connect=sqlite3.connect(self.dbpath)

    def query(self,sql:str)->list:
        """"""
        queryresult = self.connect.cursor().execute(sql).fetchall()
        return queryresult

    def queryasdict(self,sql:str)->dict:
        """调用该函数返回结果为字典形式"""
        self.connect.row_factory=self.dictfactory
        cur=self.connect.cursor()
        queryresult=cur.execute(sql).fetchall()
        return queryresult

    def insert(self,sql:str):
        print(f"执行的sql语句为\n{sql}")
        self.connect.cursor().execute(sql)
        self.connect.commit()

    def update(self,sql:str):
        self.connect.cursor().execute(sql)
        self.connect.commit()


    def delete(self,sql:str):
        self.connect.cursor().execute(sql)
        self.connect.commit()

    def closedb(self):
        self.connect.cursor().close()
        self.connect.close()

    def dictfactory(self,cursor,row):
        """将sql查询结果整理成字典形式"""
        d={}
        for index,col in enumerate(cursor.description):
            d[col[0]]=row[index]
        return d


if __name__ == '__main__':
    db=dboperate()
    # insertsql="""replace into sample_list (id,case_name,total_number,selected_number,adic,mdic_r,
    #             mdic_c,mfca,fcca,check_status,check_person,check_time,review_status,review_person,
    #             review_time,report_status,report_person,report_time)
    #             values( 'test-1','unknown',132,12,1,2,3,4,5,'已检查','admin','2020-04-22 17:22:23',
    #             '通过','admina','2020-04-22 17:22:25','已生成','admina','2020-04-22 17:26:23')"""
    sql=f"""select * from config_paras"""
    db.query(sql)
    # print(db.query("select * from sample_list"))

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网