import polars as pl
import sqlite3
conn = sqlite3.connect("test.db")
df = pl.DataFrame({"col1": [1, 2, 3]})
pl.write_database
的文档,我需要传递一个连接URI字符串,例如SQLite 数据库的“sqlite:////path/to/database.db”:
df.write_database("test_table", f"sqlite:////test.db", if_table_exists="replace")
但是,我收到以下错误:
OperationalError: (sqlite3.OperationalError) unable to open database file
这里是使用极坐标写入/读取 sqlite 表的示例。
写表到数据库(需要安装sqlalchemy).
import polars as pl
df = pl.DataFrame({"a": [1, 2, 3]})
df.write_database(
"my_table",
connection="sqlite:///database.db",
if_table_exists="replace"
)
从数据库读取表(需要安装connectorx).
pl.read_database_uri(query="SELECT * FROM my_table", uri="sqlite://database.db")
注意连接 URI 的格式。
使用 SQLite 时,斜杠的数量取决于您访问 sqlite 文件的方式。如果您按照评论中的建议使用两个斜杠,您会看到以下内容:
sqlalchemy.exc.ArgumentError: Invalid SQLite URL: sqlite://test.db
Valid SQLite URL forms are:
sqlite:///:memory: (or, sqlite://)
sqlite:///relative/path/to/file.db
sqlite:////absolute/path/to/file.db
在您的情况下,您似乎想要使用 3 个斜杠而不是 4 个。请尝试以下操作:
df.write_database("test_table", f"sqlite:///test.db", if_table_exists="replace")
这将是一个工作示例,基于您提供的示例代码片段:
import polars as pl
import sqlite3
conn = sqlite3.connect("test.db")
df = pl.DataFrame({"col1": [1, 2, 3]})
df.write_database("test_table", f"sqlite:///test.db", if_table_exists="replace")