Microsoft MVP성태의 닷넷 이야기
스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법 [링크 복사], [링크+제목 복사],
조회: 13598
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

파이썬 - pyodbc를 이용한 SQL Server 연결 사용법

PEP 249 문서에서는 paramstyle을 5가지 정의하고 있는데요, 전에 설명했던 대로 psycopg2MySQLdb는 pyformat, format 2가지 방식만 지원을 합니다.

하지만 이번 글에서 소개하는 pyodbc는 특이하게 qmark 방식만을 구현하는데요, ^^ 간단하게 우선 윈도우 환경에서 실습을 해보겠습니다.

우선 pyodbc를 설치하고,

// Microsoft 문서
// ; https://learn.microsoft.com/en-us/sql/connect/python/pyodbc/python-sql-driver-pyodbc

// ODBC Driver 18.0 for SQL Server Released
// ; https://techcommunity.microsoft.com/t5/sql-server-blog/odbc-driver-18-0-for-sql-server-released/ba-p/3169228

// pyodbc: https://pypi.org/project/pyodbc/
c:\temp> python -m pip install pyodbc

예제 코드를 작성해 실행하면 끝입니다. ODBC니까 다양하게 접속할 수 있지만 여기서는 (pymssql로도 가능한) Microsoft SQL Server로의 예제를 작성해 보겠습니다.

import pyodbc

connection_string = "Driver={SQL Server};Server=10.10.10.5;Database=TestDB;Uid=sa;Pwd=testpw;"

conn = pyodbc.connect(connection_string)
cursor = conn.cursor()

cursor.execute("SELECT * FROM mytable WHERE age > ?", 1)
row = cursor.fetchone() 
while row: 
    print(row)
    row = cursor.fetchone()

conn.close()

보는 바와 같이 "qmark" 형식의 쿼리를 실행했고, "?"에 대응하는 인자를 execute 함수에 함께 전달하면 됩니다.




참고로, 리눅스의 경우 단순히 "pip install pyodbc" 설치만 하면 사용 시 이런 오류가 발생합니다.

"libodbc.so.2: cannot open shared object file: No such file or directory" 

문서에도 자세하게 나오지만 unixodbc 설치하면 됩니다. ^^

// WSL + Ubuntu 20.04

$ sudo apt install unixodbc

또한, 이 글의 예제로 든 Microsoft SQL 서버로 연결하는 코드를 실행하면 한 번 더 에러가 발생하는데요,

$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    conn = pyodbc.connect(connection_string)
pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'SQL Server' : file not found (0) (SQLDriverConnect)")

오류 원인은, 연결 문자열인 "Driver={SQL Server};...[생략]...;"에 지정한 "SQL Server" 드라이버가 "DATA SOURCES"에 등록이 안 돼 있기 때문입니다.

$ odbcinst -j
unixODBC 2.3.11
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /home/testusr/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8

$ cat /etc/odbcinst.ini
$ cat /etc/odbc.ini
$ ls -l /etc/ODBCDataSources
total 0
$ cat /home/testusr/.odbc.ini
cat: /home/testusr/.odbc.ini: No such file or directory

따라서 "Microsoft ODBC driver for SQL Server"를 설치해야 하는데요, 공식 문서에서 자세하게 설명하고 있습니다. ^^

Install the Microsoft ODBC driver for SQL Server (Linux)
; https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server

문서상으로는 비록 "Microsoft ODBC 18"의 경우 우분투에서 18.04 ~ 23.04 버전은 지원이 안 된다고 나오지만,

if ! [[ "18.04 20.04 22.04 23.04" == *"$(lsb_release -rs)"* ]];
then
    echo "Ubuntu $(lsb_release -rs) is not currently supported.";
    exit;
fi

현재는 해당 버전의 패키지가 존재하기 때문에 저 라인을 건너 뛰고 실행하시면 됩니다.

$ cat mssql_driver.sh
wget https://packages.microsoft.com/keys/microsoft.asc | sudo tee /etc/apt/trusted.gpg.d/microsoft.asc

curl https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/prod.list > /etc/apt/sources.list.d/mssql-release.list

apt-get update
ACCEPT_EULA=Y apt-get install -y msodbcsql18
# optional: for bcp and sqlcmd
ACCEPT_EULA=Y apt-get install -y mssql-tools18
echo 'export PATH="$PATH:/opt/mssql-tools18/bin"' >> ~/.bashrc
source ~/.bashrc
# optional: for unixODBC development headers
sudo apt-get install -y unixodbc-dev

$ sudo ./mssql_driver.sh

이후 "Microsoft ODBC Driver 18 for SQL Server" 이름을 가진 driver가 설치된 것을 확인할 수 있고,

$ cat /etc/odbcinst.ini
[ODBC Driver 18 for SQL Server]
Description=Microsoft ODBC Driver 18 for SQL Server
Driver=/opt/microsoft/msodbcsql18/lib64/libmsodbcsql-18.3.so.1.1
UsageCount=1

윈도우에서 실행했던 소스코드에서 연결 문자열의 Driver만 바꿔준 후,

# connection_string = "Driver={SQL Server};Server=10.10.10.5;Database=TestDB;Uid=sa;Pwd=testpw;"
connection_string = "Driver={ODBC Driver 18 for SQL Server};Server=10.10.10.5;Database=TestDB;Uid=sa;Pwd=testpw;"

실행하면 이제 다음과 같은 오류가 나옵니다. ^^;

$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    conn = pyodbc.connect(connection_string)
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 18 for SQL Server]SSL Provider: [error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed:self signed certificate] (-1) (SQLDriverConnect)')

예의 그 인증서 오류입니다. ^^ 그런데 이상하군요, 연결 문자열에서 TrustServerCertificate 또는 Encrypt 옵션을 추가하면,

connection_string = "TrustServerCertificate=true;Driver={ODBC Driver 18 for SQL Server};Server=10.10.10.5;Database=TestDB;Uid=sa;Pwd=testpw"

# 또는,

connection_string = "Encrypt=true;Driver={ODBC Driver 18 for SQL Server};Server=10.10.10.5;Database=TestDB;Uid=sa;Pwd=testpw"

실행 시 해당 옵션들이 지원이 안 되는 듯한 오류가 나옵니다.

$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    conn = pyodbc.connect(connection_string)
pyodbc.OperationalError: ('08001', "[08001] [Microsoft][ODBC Driver 18 for SQL Server]Invalid value specified for connection string attribute 'TrustServerCertificate' (0) (SQLDriverConnect)")

$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    conn = pyodbc.connect(connection_string)
pyodbc.OperationalError: ('08001', "[08001] [Microsoft][ODBC Driver 18 for SQL Server]Invalid value specified for connection string attribute 'Encrypt' (0) (SQLDriverConnect)")

왜냐하면 윈도우 환경의 연결 문자열과는 달리 "True/False"가 아닌 pyodbc가 정한 "Yes/No"로 값을 설정해야 하기 때문입니다. ^^;

// PYODBC + MS SQL SERVER connection with Encrypt=yes not connecting
// ; https://stackoverflow.com/questions/62390326/pyodbc-ms-sql-server-connection-with-encrypt-yes-not-connecting

connection_string = "TrustServerCertificate=Yes;Driver={ODBC Driver 18 for SQL Server};Server=10.10.10.5;Database=TestDB;Uid=sa;Pwd=testpw"

# 또는,

connection_string = "Encrypt=No;Driver={ODBC Driver 18 for SQL Server};Server=10.10.10.5;Database=TestDB;Uid=sa;Pwd=testpw"

정리하면, 리눅스 환경의 경우 다음과 같은 예제 코드로 테스트하시면 됩니다.

import pyodbc

connection_string = "Driver={ODBC Driver 18 for SQL Server};Server=10.10.10.5;Database=TestDB;Uid=sa;Pwd=testpw;TrustServerCertificate=Yes"

conn = pyodbc.connect(connection_string)
cursor = conn.cursor()

cursor.execute("SELECT * FROM mytable WHERE age > ?", 1)
row = cursor.fetchone() 
while row: 
    print(row)
    row = cursor.fetchone()

conn.close()




참고로, 이러한 5가지 유형의 parameterized query를 변환해 주는 패키지가 있습니다.

SQL Params
; https://python-sql-parameters.readthedocs.io/en/latest/sqlparams.html




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/3/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11837정성태3/6/201939807기타: 74. 도서: 시작하세요! C# 7.3 프로그래밍 [10]
11836정성태3/5/201923377오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201921852.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920648개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921202개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201917118오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916946오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916634오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918326개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926235개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919167오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919352오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924624개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201919052오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920652오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201919012오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919754오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922829오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922089Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920181VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916531오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201920000Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918230오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201917072오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918377.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915702오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...