성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수</h1> <p> psycopg2를 이용하는 경우,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 파이썬 - PostgreSQL 환경 구성 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/13077'>https://www.sysnet.pe.kr/2/0/13077</a> </pre> <br /> 다음과 같은 같이 코딩하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > def test_postgre(): import psycopg2 <span style='color: blue; font-weight: bold'>with</span> psycopg2.connect(...[생략]...) as db: <span style='color: blue; font-weight: bold'>with</span> db.cursor() as cursor: sql = "SELECT * FROM TestTable" cursor.execute(sql) </pre> <br /> with로 사용한 db 연결 개체가 닫히지 않는 현상이 있습니다. 실제로 저 코드를 실행하는 웹 페이지를 방문한 후 PostgreSQL CLI를 통해 <a target='tab' href='https://www.sysnet.pe.kr/2/0/12194#pg_stat_activity'>pg_stat_activity</a> 테이블을 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > # <span style='color: blue; font-weight: bold'>/usr/bin/psql</span> psql (11.2 (Debian 11.2-1.pgdg90+1)) Type "help" for help. root=# <span style='color: blue; font-weight: bold'>select client_addr, client_port from pg_stat_activity;</span> client_addr | client_port ----------------+------------- 192.168.100.50 | 33380 192.168.100.50 | 37612 192.168.100.50 | 59440 192.168.100.50 | 40936 192.168.100.50 | 48864 192.168.100.50 | 41622 192.168.100.50 | 47890 192.168.100.50 | 33652 | -1 172.17.0.1 | 41070 | </pre> <br /> 예제를 실행한 192.168.100.50 측에서의 연결 개체가 남아 있는 것을 볼 수 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <a name='closing'></a> <br /> 이에 대한 해답은 ^^;<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > How to Work with PostgreSQL in Python ; <a target='tab' href='https://khashtamov.com/en/postgresql-with-python-and-psycopg2/'>https://khashtamov.com/en/postgresql-with-python-and-psycopg2/</a> </pre> <br /> with와 함께 closing을 함께 써줘야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > def test_postgre(): import psycopg2 <span style='color: blue; font-weight: bold'>from contextlib import closing</span> with <span style='color: blue; font-weight: bold'>closing</span>(psycopg2.connect(...[생략]...)) as db: with db.cursor() as cursor: sql = "SELECT * FROM TestTable" cursor.execute(sql) </pre> <br /> 실제로 저렇게 처리한 후에는 pg_stat_activity가 조용해졌습니다. ^^<br /> <br /> 다른 db provider도 그런 식일까요? 일례로 <a target='tab' href='https://www.sysnet.pe.kr/2/0/12851#with'>제가 테스트한 mysql의 경우</a>에는,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > with MySQLdb.connect(...[생략]...) as conn: conn.encoding = 'utf8' with conn.cursor() as cursor: query = "SELECT * FROM mytable;" cursor.execute(query) </pre> <br /> (closing 없이도) 연결 개체를 잘 정리합니다. 마찬가지로 <a target='ta' href='https://www.sysnet.pe.kr/2/0/12877#with'>pymysql도 with 구문이 적용</a>됐습니다. 다른 예로는, <a target='tab' href='https://www.sysnet.pe.kr/2/0/12848#with'>sqlite3</a>의 경우 아예 지원이 안 되었죠! 이러한 처리가 <a target='tab' href='https://peps.python.org/pep-0249/'>dbapi2</a> 명세에서 지정하지 않아 그런 것인지는 모르겠지만 암튼 with에 대한 처리를 할 때는 꼭 문서를 확인하든가, 직접 테스트를 해보는 것이 좋겠습니다. ^^;<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1079
(왼쪽의 숫자를 입력해야 합니다.)