Python讀取SQLite3數(shù)據(jù)庫中的文件并獲取列名/字段名
文件列表:
mytest.db
id timestamp
1 2022-6-17 17:59
2 2022-6-17 17:59
3 2022-6-17 17:59
4 2022-6-17 17:59
5 2022-6-17 17:59
6 2022-6-19 17:38
7 2022-6-19 17:38
8 2022-6-19 17:38
9 2022-6-19 17:38
SQLite3Test.py
# coding:utf-8 # @Time:2022-06-20 12:28 # @Author:Kevin # @Software:PyCharm import sqlite3 as sl # 獲取列名/字段名 db = sl.connect('mytest.db') cur = db.cursor() cur.execute("select * from table_data") col_name_list = [tuple[0] for tuple in cur.description] print(col_name_list) # cur.execute("PRAGMA table_info(table_data)") # print(cur.fetchall())
知識延展
1.Python獲取SQLite3數(shù)據(jù)庫的表名及字段信息
該Python代碼示例展示了如何使用sqlite3庫連接到SQLite數(shù)據(jù)庫mydb.db,獲取所有表的名稱以及每個表的字段名。首先,通過執(zhí)行SQL查詢獲取表名,然后對每個表使用PRAGMA命令獲取其列名,將結(jié)果存儲為元組列表。
# 獲取sqlite3數(shù)據(jù)庫mydb.db中的表名和表字段名 import sqlite3 def sqlite_void(): conn = sqlite3.connect('d:/data/mydb.db') cur = conn.cursor() # 獲取表名,保存在table_name列表 cur.execute("select name from sqlite_master where type='table'") rows = cur.fetchall() table_name = [row[0] for row in rows] # 獲取表的列名(字段名),保存在col_names列表,每個表的字段名集為一個元組 col_names = [] for i in table_name: cur.execute('pragma table_info({})'.format(i)) col_name = cu.fetchall() col_name = [x[1] for x in col_name] col_name = tuple(col_name) col_names.append(col_name) if __name__ == '__main__': sqlite_void()
2.使用python讀取SQLite表個并生成pdf文件
代碼用于創(chuàng)建含50列的SQLite數(shù)據(jù)庫并插入500行隨機浮點數(shù)據(jù),隨后讀取數(shù)據(jù),通過ReportLab生成橫向PDF表格,包含格式化(兩位小數(shù))及表頭、網(wǎng)格線等美觀樣式。
完整代碼
# 導(dǎo)入所需庫 import sqlite3 # 用于操作SQLite數(shù)據(jù)庫 import random # 用于生成隨機數(shù)據(jù) from reportlab.lib.pagesizes import landscape, letter # 報表實驗室?guī)欤喉撁娉叽纾M向letter紙) from reportlab.platypus import SimpleDocTemplate, LongTable # 報表實驗室組件:文檔模板、長表格 from reportlab.lib import colors # 報表實驗室顏色庫 from reportlab.lib.styles import getSampleStyleSheet # 報表實驗室預(yù)定義樣式 # ==================== 步驟1:創(chuàng)建數(shù)據(jù)庫并生成測試數(shù)據(jù) ==================== # 連接到SQLite數(shù)據(jù)庫(如果不存在則自動創(chuàng)建) conn = sqlite3.connect('mydatabase.db') # 創(chuàng)建數(shù)據(jù)庫游標對象,用于執(zhí)行SQL語句 c = conn.cursor() # 動態(tài)生成50個列名(col1到col50) columns = [f'col{i+1}' for i in range(50)] # 構(gòu)建創(chuàng)建表的SQL語句:50個REAL類型(浮點數(shù))的列 create_table_sql = f'CREATE TABLE IF NOT EXISTS tab1 ({", ".join([f"{col} REAL" for col in columns])})' # 執(zhí)行SQL語句創(chuàng)建表(IF NOT EXISTS避免重復(fù)創(chuàng)建報錯) c.execute(create_table_sql) # 生成500行隨機數(shù)據(jù)(每行50個0-100之間的浮點數(shù)) data = [] for _ in range(500): # 循環(huán)500次生成500行 # 每行包含50個隨機浮點數(shù)(范圍0-100) row = [random.uniform(0, 100) for _ in range(50)] data.append(row) # 使用executemany批量插入數(shù)據(jù)(比循環(huán)execute更高效) # SQL語句中的?是占位符,對應(yīng)data中的每個元素 c.executemany(f'INSERT INTO tab1 VALUES ({", ".join(["?"]*50)})', data) # 提交事務(wù)(將緩存中的數(shù)據(jù)寫入數(shù)據(jù)庫) conn.commit() # 關(guān)閉數(shù)據(jù)庫連接 conn.close() # ==================== 步驟2:從數(shù)據(jù)庫讀取數(shù)據(jù) ==================== # 重新連接數(shù)據(jù)庫(因為之前已關(guān)閉) conn = sqlite3.connect('mydatabase.db') c = conn.cursor() # 執(zhí)行查詢語句獲取所有數(shù)據(jù) c.execute('SELECT * FROM tab1') # 獲取所有查詢結(jié)果(返回元組的列表,每個元組代表一行數(shù)據(jù)) rows = c.fetchall() # 獲取表的列名(通過cursor.description屬性,每個元素的第一個值是列名) columns = [desc[0] for desc in c.description] # 關(guān)閉數(shù)據(jù)庫連接 conn.close() # ==================== 步驟3:生成PDF報表 ==================== # 創(chuàng)建PDF文檔模板(橫向letter紙尺寸,文件名為tab1_data.pdf) doc = SimpleDocTemplate("tab1_data.pdf", pagesize=landscape(letter)) # 獲取預(yù)定義的文本樣式(用于表格內(nèi)容) styles = getSampleStyleSheet() # 格式化數(shù)據(jù)為字符串(保留2位小數(shù),提高可讀性) formatted_rows = [] for row in rows: # 將每個單元格的浮點數(shù)格式化為"%.2f"形式的字符串 formatted_row = [f"{cell:.2f}" for cell in row] formatted_rows.append(formatted_row) # 在表格頂部插入表頭行(使用原始列名) formatted_rows.insert(0, columns) # 創(chuàng)建長表格(支持跨頁顯示) # colWidths參數(shù)設(shè)置每列寬度(這里每列固定80點,總寬度50 * 80=4000點,適合橫向紙) table = LongTable(formatted_rows, colWidths=[80] * 50) # 設(shè)置表格樣式(通過元組列表定義不同區(qū)域的樣式) table.setStyle([ # 表頭區(qū)域樣式(第0行,所有列) ('BACKGROUND', (0,0), (-1,0), colors.grey), # 背景色(灰色) ('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke), # 文字顏色(白色) ('ALIGN', (0,0), (-1,-1), 'CENTER'), # 所有單元格文字居中 ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'), # 表頭字體(加粗) ('BOTTOMPADDING', (0,0), (-1,0), 12), # 表頭底部內(nèi)邊距(12點) # 數(shù)據(jù)行區(qū)域樣式(第1行到最后一行,所有列) ('BACKGROUND', (0,1), (-1,-1), colors.beige), # 背景色(米色) # 全局網(wǎng)格線樣式(所有單元格) ('GRID', (0,0), (-1,-1), 1, colors.black), # 網(wǎng)格線寬度1點,黑色 # 全局垂直對齊方式(所有單元格頂部對齊) ('VALIGN', (0,0), (-1,-1), 'TOP') ]) # 將表格添加到PDF文檔并構(gòu)建輸出 doc.build([table]) # 輸出完成提示 print("PDF已成功生成: tab1_data.pdf")
到此這篇關(guān)于Python讀取SQLite3數(shù)據(jù)庫中的文件并獲取列名/字段名的文章就介紹到這了,更多相關(guān)Python讀取SQLite3內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 標準庫time時間的訪問和轉(zhuǎn)換問題小結(jié)
time 模塊為 Python 提供了處理時間和日期的多種功能,適用于多種與時間相關(guān)的場景,包括獲取當前時間、格式化時間、暫停程序執(zhí)行、計算程序運行時長等,這篇文章主要介紹了Python 標準庫time時間的訪問和轉(zhuǎn)換,需要的朋友可以參考下2025-01-01對python中不同模塊(函數(shù)、類、變量)的調(diào)用詳解
今天小編就為大家分享一篇對python中不同模塊(函數(shù)、類、變量)的調(diào)用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07python+webdriver自動化環(huán)境搭建步驟詳解
在本篇文章里小編給大家分享了關(guān)于python+webdriver自動化環(huán)境搭建的詳細步驟以及注意點,需要的朋友們參考下。2019-06-06pydantic?resolve解決嵌套數(shù)據(jù)結(jié)構(gòu)生成痛點分析
這篇文章主要為大家介紹了pydantic?resolve解決嵌套數(shù)據(jù)結(jié)構(gòu)生成痛點分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04