brunch

You can make anything
by writing

C.S.Lewis

by 유윤식 Jun 19. 2024

Python: DuckDB(5)

#Postgresql #Plugin

DuckDB 에서 Posgresql 에 연결된 Database, DB, Table 에 접근하고

바로 쿼리를 날려볼 수 있다.

https://duckdb.org/docs/guides/database_integration/postgres


먼저 macos(intel version) 에서 brew 를 통해서 Postgres 를 설치하고

서비스로 등록하면 끝!


>> brew install postgresql

>> brew services start postgresql


이러면 default 설정으로 잡혀있는데 다시 터미널에서


>> psql postgres

>># CREATE DATABASE mydatabase;

>># CREATE USER 'YOUR_NAME' WITH ENCRYPTED PASSWORD 'YOUR_PWD'

>># GRANT ALL PRIVILEGES ON DATABASE mydatabase TO 'YOUR_NAME';


이러면 mydatabase 데이터베이스가 생성된다.


이제 쥬피터에서 해당 Postgres 에 접속해서 테이블에 쿼리를 보내보자.


DuckDB 와 연결을 위해서 필요한 라이브러리를 설치하고,

>> pip install jupysql pandas matplotlib duckdb-engine psycopg2-binary


간단하게 Postgre 에 테이블을 만들어서 간단한 데이터를 넣어본다.



import psycopg2

from contextlib import contextmanager


@contextmanager

def get_db_connection(dbname, user, password, host="localhost", port="5432"):

    conn = None

    try:

        conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port)

        yield conn

    finally:

        if conn:

            conn.close()


@contextmanager

def get_db_cursor(dbname, user, password, host="localhost", port="5432"):

    conn = None

    try:

        conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port)

        cursor = conn.cursor()

        yield cursor

        conn.commit()

    except Exception as e:

        if conn:

            conn.rollback()

        raise e

    finally:

        if cursor:

            cursor.close()

        if conn:

            conn.close()


# 데이터베이스 설정

dbname = "mydatabase"

user = "YOUR_NAME"

password = "YOUR_PWD"

host = "localhost"

port = "5432"


# 데이터베이스 작업 수행

with get_db_cursor(dbname, user, password, host, port) as cur:

    # 테이블 생성

    cur.execute("""

        CREATE TABLE IF NOT EXISTS test_table (

            id SERIAL PRIMARY KEY,

            name VARCHAR(100),

            age INT

        )

    """)


    # 데이터 삽입

    cur.execute("INSERT INTO test_table (name, age) VALUES (%s, %s)", ("Alice", 30))

    cur.execute("INSERT INTO test_table (name, age) VALUES (%s, %s)", ("Bob", 25))


# 데이터 조회

with get_db_cursor(dbname, user, password, host, port) as cur:

    cur.execute("SELECT * FROM test_table")

    rows = cur.fetchall()

    for row in rows:

        print(row)


이런 결과가 프린트된다.

>> (1, 'Alice', 30) (2, 'Bob', 25)


이제 DuckDB 로 조회!


새로운 connnection (예를 들어, con2 로 duckdb 엔진에 하나 더 붙여서) 을 통해서 sqlite 에 있는 테이블도 읽어서 사용 가능하다.

https://duckdb.org/docs/guides/database_integration/sqlite


작가의 이전글 Polars #09
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari