Python SQlite如何检查导入文件的数量

8cdiaqws  于 2023-01-04  发布在  Python
关注(0)|答案(1)|浏览(116)

我已经用Python把数据导入到一个SQLite3数据库中,我有15个表。
我想检查每个表中的结果,并为加载的每个文件计数。

    • 预期结果:**
+---------------+------------+-------------------------------------------+
|  Tablename    |  #Records  |              FilenameImported             |
+---------------+------------+-------------------------------------------+
| Tbl_RawData1  |     23680  |  442953-63fe-45fd-8378-c5f5fe5cb755.csv   |
| Tbl_RawData2  |     13358  |  bd3e609f-999f-4d29-845d-107bd5e205d6.csv |
| Tbl_RawData3  |     25000  |  Import.csv                               |
| Tbl_RawData4  |     15000  |  Importbis.csv                            |
+---------------+------------+-------------------------------------------+
...
    • 在dbeaver中使用的查询下面。**
select count(FileBase), FileBase from Tbl_RawData1 group by Filebase
select count(FileBase), FileBase from Tbl_RawData2 group by Filebase
select count(FileBase), FileBase from Tbl_RawData3 group by Filebase
select count(FileBase), FileBase from Tbl_RawData4 group by Filebase
select count(FileBase), FileBase from Tbl_RawData5 group by Filebase
...

在Python中做这件事的最好方法是什么?

nhhxz33t

nhhxz33t1#

在这个帖子中的答案学分:List of tables, db schema, dump etc using the Python sqlite3 API

def overview_tables(path, database):
    try:
        dbname = os.path.join(path, database)
        print("INITILIZATION COUNT IMPORT FILES FOR EACH TABLE...")
        con = sqlite3.connect(dbname)
        cursor = con.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = cursor.fetchall()
        for tbl in tables:
            print("\n########  " + tbl[0] + "  ########")
            # cursor.execute("SELECT * FROM "+tbl[0]+";") #print all columns
            cursor.execute("select count(FileBase), FileBase from " + tbl[0] + " group by FileBase") #print count per geimporteerde file
            rows = cursor.fetchall()
            for row in rows:
                print(row)
        print(cursor.fetchall())
    except KeyboardInterrupt:
        print("\nClean Exit By user")
    finally:
        print("\nFinally")

相关问题