-
Ubuntu 환경에서 ODBC를 통해 Tibero와 Python 연동하기Tibero DB (Tmax AI Bigdata Academy) 2023. 10. 16. 21:31
지난번에 WSL을 통해 윈도우에 설치한 Ubuntu에다가 Tibero6를 설치를 했었다.
교육을 들으면서 차후 진행할 프로젝트 3가지 주제 중에서
이미지 분석 AI 모델을 활용해서 제공하는 서비스를 선택하게되어
이번에는 Tibero6와 Python을 연동해보려고한다.
아무래도 파이썬이 필요할테니!
사실 나중에 가서 혹시나 바뀔수도 있겠지만.. 미리 연동해놓는게 마음이 편할거 같다.
연동하기 앞서서, Python에는 여러 데이터베이스와의 연동을 지원하는 라이브러리가 있지만
아직까지 Tibero와 연동을 지원하는 라이브러리는 없는 것으로 보인다. Tibero 공식 문서에서도 ODBC를 통해 연동하도록 설명하고 있었다. 아래 사진처럼 Tibero는 ODBC, JDBC 등등 여러가지를 지원하여 Listener를 거쳐
클라이언트의 새로운 접속 요청을 받아 이를 유효한 워커 프로세스에 할당하는 구조를 가지고 있다.
Ubuntu에 ODBC 설치하기
$ sudo apt install unixodbc $ sudo apt install odbcinst
설치되었는지 확인하기
$ which isql $ odbcinst -j
참고로 Linux 운영체제에서는 시스템 DSN과 사용자 DSN 설정 파일의 경로가 다르다.
위 그림처럼 시스템 DSN 설정은 /etc/odbc.ini이고 사용자 DSN 설정은 ~/.odbc.ini에서 수행한다.
ODBC 드라이버 설정하기
tibero6를 설치한 경로를 보면 tibero6/client/lib에 libtbodbc.so라는 파일이 존재한다.
이는 Tibero에서 제공하고 있는 ODBC 드라이버이다.
참고로 나의 경우 /home 에서 tibero라는 폴더를 만들어, 이 안에 tibero6 파일들을 넣었기 때문에
나의 절대 경로는 /home/tibero/tibero6/client/lib/libtbodbc.so 이다.
이제 이 드라이버를 사용하기 위해서는 odbcinst.ini 파일에 해당 드라이버의 경로를 적어줘야한다.
그러므로 vi 편집기를 통해서 드라이버 경로를 작성해주자
$sudo vi /etc/odbcinst.ini
아래 내용 작성하고 :wq
[Tibero6Driver] Description = Tibero6 ODBC driver Driver = /home/tibero/tibero6/client/lib/libtbodbc.so Setup = /home/tibero/tibero6/client/lib/libtbodbc.so FileUsage = 1
참고로 대괄호[] 안의 Tibero6Driver 문자열은 임의로 정한 값이기 때문에 다르게 작성해도된다.
드라이버의 경로를 가리키는 이름이라고 생각해주면 된다.
바로 다음 odbc.ini 파일을 작성할 때 명시해 줄 것이니 기억하고 있자
odbc.ini 작성
[ODBC] 아래에는 로그 파일의 추적 여부와 추적 단계, 추적 파일 경로를 작성하고
그 아래에는 DSN 연결을 위해 필요한 정보들을 작성해준다. 나의 경우 DSN 이름을 [tibero]로 설정해주었다.
[ODBC] Trace = 1 TraceFile = /home/tibero/iodbc/log/odbc.trace [tibero] # DSN 이름 (대괄호 안의 이름은 임의로 설정해줘도 된다) Trace = no Driver = Tibero6Driver # odbcinst.ini에서 작성했던 Tibero 드라이버 경로 이름. 사실 직접 절대경로 써도됨 Description = Tibero6 ODBC Datasource SERVER = 0.0.0.0 # Tibero가 위치한 서버 IP PORT = 8629 # Tibero가 위치한 서버 PORT SID = tibero # tbdsn.tbr 참고 User = sys # 접속할 Tibero의 유저 Password = tibero # 접속할 Tibero 유저의 패스워드 Database = tibero # 접속할 Tibero DB Name (tbdsn.tbr 참고)
여기서 SID와 Database는 Tibero6가 설치된 폴더안의 tibero6/client/config 경로에 위치하는
tbdsn.tbr을 참조하면 된다. 아래 내용은 개인 마다 다를 수 있으니 직접 살펴보길 권장
(이 게시글과는 번외로 tbdsn.tbr에서 로드 밸런싱 기능을 설정할 수 있다고 하니 아래 링크 참고바람)
위 과정까지 끝났으면 ODBC를 통해 Tibero에 접근이 가능한지 확인해보자
앞서 unixodbc 패키지를 설치하면 isql을 통해 테스트가 가능하다.
$ isql [odbc.ini에서 설정해준 DSN 이름]
위와 같이 Tibero에 미리 만들어 두었던 s_dept 테이블이 select query문을 통해
잘 나오는 것을 확인할 수 있다.
Python3 pyodbc 설치하기
이제 ODBC를 통해 Tibero에 접근이 가능한 것을 확인했으니 pyodbc를 통해
Python과 Tibero를 연동해보자
나의 경우 기본적으로 Ubuntu에 python3이 설치되어있었다.
python3 버전은 아래와 같다.
pyodbc를 설치하기 위해서는 아래 명령어를 차례로 입력해 설치해준다.
g++을 설치해주는 이유는, pyodbc의 경우 C++ extensions들이 포함되어 있기 때문에 필수로 설치해줘야 한다.
$ sudo apt-get update $ sudo apt-get install g++ unixodbc-dev $ sudo apt-get install python3-pip $ pip3 install --user pyodbc
Python 코드 작성 및 실행하기
이제 다 왔다!!
$ sudo vi test.py import pyodbc try: user = 'sys' passwd = 'tibero' sql = 'select * from s_dept;' conn = pyodbc.connect('DSN=tibero;UID='+user+';PWD='+passwd) conn.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8') # 인코딩 문제 해결하기 위함 (필수 작성) conn.setdecoding(pyodbc.SQL_WCHAR, encoding='utf-8')# 인코딩 문제 해결하기 위함 (필수 작성) conn.setdecoding(pyodbc.SQL_WMETADATA, encoding='utf-32le')# 인코딩 문제 해결하기 위함 (필수 작성) conn.setencoding(encoding='utf-8') curs = conn.cursor() row = curs.execute(sql) for i in row: print(i[0], i[1], i[2]) # s_dept의 column이 총 3개이므로 다음과 같이 작성했음 conn.close() except Exception as ex: print(ex)
이제 파이썬 코드를 실행해보자!!
$ python3 test.py
위와 같이 s_dept 테이블에 존재하는 값들을 성공적으로 가져오는 것을 볼 수 있다!!!!!!!!
(여러번의 삽질을 거쳐 드디어 성공...)
이제 드디어 Python과 Tibero6를 활용한 개발 시작~
+ 2023-11-18 오류 해결
1. pyodbc.Error: ('I000', '[I000] (-2048) (SQLDriverConnect)')
AWS LightSail 인스턴스 두개를 생성해서 하나의 인스턴스에는 Tibero6를 설치하고,
또다른 인스턴스에는 AI 이미지 인식 관련 작업을 하기 위해 pyodbc를 설치하여 Tibero6와 연동하려했는데
Traceback (most recent call last): File "<stdin>", line 1, in <module> pyodbc.Error: ('I000', '[I000] (-2048) (SQLDriverConnect)')
위와 같은 오류가 발생했다.
당시에 Python3의 버전은 3.8.10 이였고, pyodbc 버전은 5.0.1이였다.
분명 pyodbc 공식 문서에서 5.0.1에 호환되는 버전은 3.8 이상이여서 문제 없을거라 판단했는데, 위와 같은 오류가 발생한 것이다.
pyodbc 5.0.1 버전의 문제는 아니겠지하고 계속 몇시간째 삽질하다가 도저히 안될거 같아 버전을 낮춰보기로 했다.
pre-relase 버전이 아닌, pyodbc 4.0.39 버전으로 변경 후 다시 Tibero6와 연동해보니 문제가 해결되었다....
2. 'utf-8' codec can't decode byte 0xc0 in position 0: invalid start byte
pyodbc를 사용하는 python 코드에서
디코딩 설정을 'euc-kr'로 변경해주자.
Reference
https://pypi.org/project/pyodbc/4.0.39/
https://github.com/mkleehammer/pyodbc/wiki/Install
https://blog.boxcorea.com/wp/archives/2881
'Tibero DB (Tmax AI Bigdata Academy)' 카테고리의 다른 글
Spring Boot JPA와 Tibero6 연동 간 발생했던 에러들 정리 (0) 2023.11.11 Spring Boot JPA를 통해 Tibero6와 연동하기 (0) 2023.10.28 tbstudio 실행 및 기능 살펴보기 (0) 2023.10.22 pyodbc를 이용하여 Tibero DB에 대한 query문 작성하기 (0) 2023.10.17 티베로 데이터베이스 설치하기 Tibero install in Ubuntu(WSL) (0) 2023.10.14