如何在Python中使用Polars写入SQLite数据库?

问题描述 投票:0回答:2
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
python sqlite python-polars
2个回答
1
投票

这里是使用极坐标写入/读取 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://)
  • sqlite:///relative/path/to/file.db
  • sqlite:////绝对/路径/to/file.db
  • sqlite:///c:/absolute/path/on/windows/file.db(归功于@Thomas)

0
投票

使用 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")
© www.soinside.com 2019 - 2024. All rights reserved.