이 빠른 시작에서는 Python 사용하여 Azure HorizonDB 인스턴스에 연결합니다. 그런 다음, SQL 문을 사용하여 macOS, Ubuntu Linux 및 Windows 플랫폼에서 데이터베이스의 데이터를 쿼리, 삽입, 업데이트 및 삭제합니다.
이 문서의 단계에는 PostgreSQL 인증이 포함됩니다.
PostgreSQL 인증은 PostgreSQL에 저장된 계정을 사용하며 암호 회전을 직접 관리해야 합니다.
이 문서에서는 Python 사용하여 개발하는 데 익숙하지만 Azure HorizonDB를 사용하는 것은 익숙하지 않은 것으로 가정합니다.
사전 요구 사항
- 활성 구독이 있는 Azure 계정. 무료로 계정을 만듭니다.
- Azure HorizonDB 클러스터입니다. Azure HorizonDB 클러스터를 만들려면 Azure HorizonDB 클러스터 만들기 참조하세요.
- Python 3.8 이상.
- 최신 pip 패키지 설치 관리자.
클라이언트 워크스테이션에 대한 방화벽 규칙 추가
- Public 액세스(허용된 IP 주소) 사용하여 Azure HorizonDB 클러스터를 만든 경우 클러스터의 방화벽 규칙 목록에 로컬 IP 주소를 추가할 수 있습니다. Azure HorizonDB의 네트워크(미리 보기) 참조하세요.
개발 환경 준비
코드를 실행하려는 폴더로 변경하고 가상 환경을 만들고 활성화합니다. 가상 환경은 특정 버전의 Python과 해당 애플리케이션에 필요한 기타 패키지를 위한 자체 포함 디렉터리입니다.
다음 명령을 실행하여 가상 환경을 만들고 활성화합니다.
py -3 -m venv .venv
.venv\Scripts\activate
Python 라이브러리 설치
코드 예를 실행하는 데 필요한 Python 라이브러리를 설치합니다.
PostgreSQL 데이터베이스에 연결하고 쿼리할 수 있는 psycopg 모듈을 설치합니다.
# Recommended: install the binary wheel that bundles a compatible libpq wrapper (Windows/macOS)
python -m pip install "psycopg[binary]"
# Linux alternative (if you prefer building against system libpq):
sudo apt-get update
sudo apt-get install -y libpq-dev build-essential python3-dev
python -m pip install psycopg
인증 코드 추가
이 섹션에서는 작업 디렉터리에 인증 코드를 추가하고 클러스터 인스턴스로 인증 및 권한 부여에 필요한 추가 단계를 수행합니다.
인증 코드를 추가하기 전에 각 예제에 필요한 패키지가 설치되어 있는지 확인합니다.
필수 패키지(이 문서의 예제):
- 암호 예제:
psycopg(권장:python -m pip install "psycopg[binary]")
선택 사항: 재현 가능한 설치를 위해 다음 항목으로 requirements.txt를 만들고 python -m pip install -r requirements.txt로 설치합니다.
다음 코드를 편집기에 복사하고 get_conn.py라는 파일에 저장합니다.
import urllib.parse import os def get_connection_uri(): # Read URI parameters from the environment dbhost = os.environ['DBHOST'] dbname = os.environ['DBNAME'] dbuser = urllib.parse.quote(os.environ['DBUSER']) password = os.environ['DBPASSWORD'] sslmode = os.environ['SSLMODE'] db_uri = f"host={dbhost} dbname={dbname} user={dbuser} password={password} sslmode={sslmode}" # Construct connection URI return db_uri데이터베이스 연결 정보를 가져옵니다.
Azure Portal 사용:
연결 URI 요소에 대한 환경 변수를 설정합니다.
set DBHOST=<cluster-name> set DBNAME=<database-name> set DBUSER=<username> set DBPASSWORD=<password> set SSLMODE=require
Python 예제를 실행하는 방법
이 문서의 각 코드 예제는 다음과 같습니다.
텍스트 편집기에서 새 파일을 만듭니다.
파일에 코드 예제를 추가합니다.
프로젝트 폴더의 파일을 .py 확장명을 사용하여 저장합니다(예: postgres-insert.py). Windows의 경우 파일을 저장할 때 UTF-8 인코딩을 선택해야 합니다.
프로젝트 폴더에서
python을 입력하고 그 뒤에 파일 이름을 입력합니다(예:python postgres-insert.py).
테이블 만들기 및 데이터 삽입
다음 코드 예제에서는 psycopg.connect 함수를 사용하여 Azure HorizonDB 클러스터에 연결하고 SQL INSERT 문을 사용하여 데이터를 로드합니다.
cursor.execute 함수는 데이터베이스에 대해 SQL 쿼리를 실행합니다.
import psycopg
from get_conn import get_connection_uri
conn_string = get_connection_uri()
conn = psycopg.connect(conn_string)
print("Connection established")
cursor = conn.cursor()
# Drop previous table of same name if one exists
cursor.execute("DROP TABLE IF EXISTS inventory;")
print("Finished dropping table (if existed)")
# Create a table
cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
print("Finished creating table")
# Insert some data into the table
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
print("Inserted 3 rows of data")
# Clean up
conn.commit()
cursor.close()
conn.close()
코드가 성공적으로 실행되면, 다음 출력을 생성합니다.
Connection established
Finished dropping table (if existed)
Finished creating table
Inserted 3 rows of data
데이터 읽기
다음 코드 예제에서는 Azure HorizonDB 클러스터에 연결하고 SQL SELECT 문과 함께 cursor.execute를 사용하여 데이터를 읽습니다. 이 함수는 쿼리를 허용하며, cursor.fetchall()을 사용하여 반복할 결과 집합을 반환합니다.
import psycopg
from get_conn import get_connection_uri
conn_string = get_connection_uri()
conn = psycopg.connect(conn_string)
print("Connection established")
cursor = conn.cursor()
# Fetch all rows from table
cursor.execute("SELECT * FROM inventory;")
rows = cursor.fetchall()
# Print all rows
for row in rows:
print("Data row = (%s, %s, %s)" %(str(row[0]), str(row[1]), str(row[2])))
# Cleanup
conn.commit()
cursor.close()
conn.close()
코드가 성공적으로 실행되면, 다음 출력을 생성합니다.
Connection established
Data row = (1, banana, 150)
Data row = (2, orange, 154)
Data row = (3, apple, 100)
데이터 업데이트
다음 코드 예제에서는 Azure HorizonDB 클러스터에 연결하고 SQL UPDATE 문과 함께 cursor.execute를 사용하여 데이터를 업데이트합니다.
import psycopg
from get_conn import get_connection_uri
conn_string = get_connection_uri()
conn = psycopg.connect(conn_string)
print("Connection established")
cursor = conn.cursor()
# Update a data row in the table
cursor.execute("UPDATE inventory SET quantity = %s WHERE name = %s;", (200, "banana"))
print("Updated 1 row of data")
# Cleanup
conn.commit()
cursor.close()
conn.close()
데이터 삭제
다음 코드 예제에서는 Azure HorizonDB 클러스터에 연결하고 SQL DELETE 문과 함께 cursor.execute를 사용하여 이전에 삽입한 인벤토리 항목을 삭제합니다.
import psycopg
from get_conn import get_connection_uri
conn_string = get_connection_uri()
conn = psycopg.connect(conn_string)
print("Connection established")
cursor = conn.cursor()
# Delete data row from table
cursor.execute("DELETE FROM inventory WHERE name = %s;", ("orange",))
print("Deleted 1 row of data")
# Cleanup
conn.commit()
cursor.close()
conn.close()