[英]populate SQL database with dask dataframe and dump into a file
在此 colab上重現錯誤和用例
我有多個大表,我通過 Dask (dataframe) 讀取和分析它們。 分析后,我想將它們推送到本地數據庫(在本例中為 sqlite 引擎通過 sqlalchemy package。
這是一個虛擬數據:
import pandas as pd
import dask.dataframe as dd
df = pd.DataFrame([{"i": i, "s": str(i) * 2} for i in range(4)])
ddf = dd.from_pandas(df, npartitions=2)
from dask.utils import tmpfile
from sqlalchemy import create_engine
with tmpfile(
dir="/outputs/",
extension="db",
) as f:
print(f)
db = f"sqlite:///{f}"
ddf.to_sql("test_table", db)
engine = create_engine(
db,
echo=False,
)
print(dir(engine))
result = engine.execute("SELECT * FROM test_table").fetchall()
print(result)
但是, tmpfile
文件是臨時文件,並未存儲在我的本地驅動器上。 我想將數據庫轉儲到我的本地驅動器中; 我找不到tmpfile
的任何參數以確保將其存儲為文件。 兩人都不知道如何傾倒我的引擎。
更新如果我使用普通文件,會遇到如下錯誤
return self.dbapi.connect(*cargs, **cparams)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file
(Background on this error at: https://sqlalche.me/e/14/e3q8)
這是代碼
with open(
"/outputs/hello.db", "wb"
) as f:
print(f)
db = f"sqlite:///{f}"
ddf.to_sql("test_table", db, if_exists="replace")
engine = create_engine(
db,
echo=False,
)
print(dir(engine))
result = engine.execute("SELECT * FROM test_table").fetchall()
print(result)
如果您想保存到常規文件,則無需使用上下文管理器:
import dask.dataframe as dd
import pandas as pd
df = pd.DataFrame([{"i": i, "s": str(i) * 2} for i in range(4)])
ddf = dd.from_pandas(df, npartitions=2)
OUT_FILE = "test.db"
db = f"sqlite:///{OUT_FILE}"
ddf.to_sql("test_table", db)
要測試文件是否已保存,請運行:
from sqlalchemy import create_engine
engine = create_engine(
db,
echo=False,
)
result = engine.execute("SELECT * FROM test_table").fetchall()
print(result)
# [(0, 0, '00'), (1, 1, '11'), (2, 2, '22'), (3, 3, '33')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.