arrow-odbc-py
arrow-odbc-py是从 ODBC 数据源中读取数据并返回 Arrow 数组的 Python 库。
Tips
他并不是构建在 pyodbc 上的,而是对 Rust 的arrow-odbc的 Python 包装。
基本使用
注意首先本机必须安装 ODBC 驱动管理器以及配置好对应数据源的驱动程序,之后通过连接字符串来连接:
Python
connection_string = (
"Driver=MariaDB Unicode;"
"Server=localhost;"
"Database=out;"
"Port=331;"
"UID=root;"
"PWD=WkyBN6wmHL4FjfMk6A6Fa2ar3qEZ6Vgx;"
)
Tips
他实际上就是自己添加了 DSN。
查询
Python
from arrow_odbc import read_arrow_batches_from_odbc
connection_string= "connection_string"
reader = read_arrow_batches_from_odbc(
query=f"SELECT * FROM MyTable WHERE a=?",
connection_string=connection_string,
parameters=["I'm a positional query parameter"],
batch_size=100000, # 决定了每个 Batch 返回的行数,注意受 max_bytes_per_batch 限制
max_bytes_per_batch=2**19 # 决定了每次通信返回的最大字节
)
for batch in reader:
# Process Arrow Batches
pass
插入
Python
from arrow_odbc import insert_into_table
import pyarrow as pa
import pandas
def dataframe_to_table(df):
table = pa.Table.from_pandas(df)
reader = pa.RecordBatchReader.from_batches(table.schema, table.to_batches())
insert_into_table(
connection_string=connection_string,
chunk_size=1000,
table="MyTable",
reader=reader,
)