Python - pymssql - MSSQL DB 연결, 데이터프레임으로 데이터 출력

 

이번 포스팅에서는...

MS-SQL(SQL Server)에 접속하는 방법과

Pandas를 이용하여 데이터베이스에 저장된 데이터를 데이터프레임으로 읽어와서 출력하는 방법을 설명합니다.


MSSQL DB 연결

pymssql

  • 파이썬에서 MSSQL(SQL SERVER)의 데이터베이스를 제어 할 수 있게 해주는 모듈

모듈 설치

# Windows
pip install pymssql
# conda install pymssql

# Linux
sudo pip install pymssql

# Mac
sudo -H pip install pymssql

DB 연결

import pymssql

# Connect to the database
conn = pymssql.connect(server='server_name',\
	user='user_name', password='password', database='database_name')

Pandas 데이터프레임으로 출력

  • read_sql_query : SQL 쿼리문의 결과를 데이터프레임 형식으로 반환
import pandas as pd

# conn : 설정한 DB 접속 정보

query = '쿼리문 입력'

# read_sql_query : 쿼리를 실행한 결과를 데이터프레임으로 읽어오기
data = pd.read_sql_query(query, conn)
data

사용 예시

  • MSSQL(SSMS)에서의 테이블 값 확인
select * from testTable

 

  • colab에서 pymssql 모듈을 이용하여 DB에 접속, 데이터를 데이터프레임으로 출력
import pymssql
import pandas as pd

# Connection Information
server = #host&servername
username = #username
password = #password
database = #database

# Connect to the database
conn = pymssql.connect(server=server, user=username, password=password, database=database)

data = pd.read_sql_query('select * from testTable', conn)
data


+ DB의 데이터 불러오는 간단 사용 예시

쿼리로 해당 SQL 서버에 저장된 함수의 값을 불러오기

함수는 넣은 값을 그대로 반환하는 간단한 함수임 (함수명 : testFunc)

# Connect to the database
conn = pymssql.connect(server=server, user=username, password=password, database=database)

# Get cursor
cursor = conn.cursor()

# Execute cursor
cursor.execute("select dbo.testfunc(1)")

# Data set load
row = cursor.fetchall()   

# Data commit
conn.commit()

# Cursor resources return
conn.close()


row


참고