Python API#

pip install duckdb

クエリの実行#

duckdb.sql によるクエリ

import duckdb

r = duckdb.sql("SELECT 123 as num")
r.show()
┌───────┐
│  num  │
│ int32 │
├───────┤
│   123 │
└───────┘

実行結果の変換#

Python objects

r.fetchall()
[(123,)]

Pandas DataFrame

r.df()
num
0 123

Polars DataFrame

r.pl()
shape: (1, 1)
num
i32
123

Arrow Table

r.arrow()
pyarrow.Table
num: int32
----
num: [[123]]

NumPy Arrays

duckdb.sql("SELECT 42").fetchnumpy()
{'42': array([42], dtype=int32)}

接続オプション#

インメモリデータベース#

duckdb.sql("SELECT 123 as num")
┌───────┐
│  num  │
│ int32 │
├───────┤
│   123 │
└───────┘
con = duckdb.connect()
con.sql("SELECT 123 as num")
┌───────┐
│  num  │
│ int32 │
├───────┤
│   123 │
└───────┘

永続ストレージ#

with duckdb.connect("sample.db") as con:
    con.sql("CREATE TABLE sample_table (i INTEGER)")
    con.sql("INSERT INTO sample_table VALUES (123)")
con = duckdb.connect("sample.db")
con.sql("SELECT * FROM sample_table")
┌───────┐
│   i   │
│ int32 │
├───────┤
│   123 │
└───────┘