我有一個包含 150 多個 txt 檔案的檔案夾。
合并資料
生成的檔案大小為 320 MB。我創建一個資料庫并插入組合資料:
with open("resall.TXT", "r") as f:
result = f.readlines()
result = [x.split(",") for x in result]
import sqlite3 as sq3
con = sq3.connect("popular.db")
con.execute(
"""
CREATE TABLE IF NOT EXISTS popname (
id INTEGER PRIMARY KEY,
state TEXT,
sex TEXT,
year TEXT,
forename TEXT,
count INTEGER
);
"""
)
for i, (state, sex, year, forename, count) in enumerate(result):
con.execute(
"""
INSERT INTO popname VALUES (?, ?, ?, ?, ?, ?);
""",
(i, state, sex, year, forename, count.strip()),
)
con.commit()
我無法創建資料庫,因為它太大了。如何減小資料庫的大小?
uj5u.com熱心網友回復:
問題不是 SQLite,而是您的匯入腳本。SQLite 可以輕松處理那么多資料,320 MB 并不是那么大。
第一個問題是您將所有 320 MB 的空間都放入記憶體中。相反,迭代這些行。
with open("resall.TXT", "r") as f:
for line in f:
rows = line.split(",")
// then insert
當您進行插入時,在每次插入后提交會使它顯著變慢。每次提交都會強制 SQLite 寫入緩慢的磁盤。
相反,每 1000 行左右提交一次。
for i, (state, sex, year, forename, count) in enumerate(rows):
con.execute(
"""
INSERT INTO popname VALUES (?, ?, ?, ?, ?, ?);
""",
(i, state, sex, year, forename, count.strip()),
)
if i % 1000 == 0:
con.commit()
但是,有一種更快的方法可以做到這一點。使用 SQLite 自己的內置匯入器。
- 在檔案中添加標題行,確保它們與您的列名匹配。
- 在 SQLite shell 中打開您的資料庫。
- 創建你的表。
- 將 CSV 檔案匯入您的表中:
.import /path/to/your/file.csv popname --csv
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/525570.html
標籤:Pythonsqlite
上一篇:sql命令找出多少玩家得分多少
