使用duckdb載入mysql

waketzheng發表於2024-08-19

安裝duckdb

https://duckdb.org/docs/installation/index

載入mysql擴充套件

https://duckdb.org/docs/extensions/mysql.html
離線安裝的話,可以等INSTALL mysql;超時後,根據它提示的URL到有網環境下載,再傳到伺服器掛載Nginx,修改/etc/hosts指向,再重新執行INSTALL。

Demo程式碼如下:

import duckdb

DB_HOST = "localhost"
DB_USERNAME = "root"
DB_PASS = "123456"
DB_PORT = 3306
DB_NAME = "test_1"

PARAMETERS = f"host={DB_HOST} user={DB_USERNAME} passwd={DB_PASS} port={DB_PORT} database={DB_NAME}"
ATTACH_QUERY = f"ATTACH '{PARAMETERS}' AS user (TYPE mysql);"
USE_QUERY = "USE user;"

with duckdb.connect() as con:
    con.install_extension("mysql")
    con.load_extension("mysql")
    con.sql(ATTACH_QUERY)
    con.sql(USE_QUERY)
    con.sql("SHOW TABLES").show()
    res = con.sql("select * from user;")
    res.show()
    data: list[tuple] = res.fetchall()
    print(f"fetchall: {data!r}")

相關文章