欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python讀取SQLite3數(shù)據(jù)庫中的文件并獲取列名/字段名

 更新時間:2025年07月24日 10:15:54   作者:climber1121  
這篇文章主要為大家詳細介紹了如何使用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)文章

最新評論