欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-01 15:49:14
```python import sqlite3 import os class DBOperate: def __init__(self,dbPath=os.path.join(os.getcwd(),"db")): self.dbPath=dbPath self.connect=sqlite3.... ......
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"))