250x250
Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- JDBC
- Thymeleaf
- Source
- error
- AJAX
- SpringBoot
- git
- oracle
- 오픈소스
- Docker
- 문서
- STS
- spring
- Exception
- myBatis
- Open Source
- JavaScript
- Python
- jpa
- MySQL
- PostgreSQL
- Tomcat
- MSSQL
- Core Java
- maven
- Eclipse
- IntelliJ
- Spring Boot
- ubuntu
- 설정
Archives
- Today
- Total
헤르메스 LIFE
[Python] DB Connection - MSSQL 본문
728x90
1. MSSQL Connection
참조 : hermeslog.tistory.com/501?category=306365
(venv) C:\JetBrains\pythonProject\venv\Scripts>pip install pymssql-2.1.5-cp39-cp39-win_amd64.whl Processing c:\jetbrains\pythonproject\venv\scripts\pymssql-2.1.5-cp39-cp39-win_amd64.whl Installing collected packages: pymssql Successfully installed pymssql-2.1.5 |
2. Sample
2-1. Sample-01
import pymssql
config = {
'server': '서버IP',
'port': '포트',
'user': '아이디',
'password': '패스워드',
'database': 'DB명',
'charset': 'utf8'
}
# Construct connection string
try:
conn = pymssql.connect(**config)
except Exception as err:
print(err)
raise
else:
cursor = conn.cursor()
cursor.execute('SELECT @@version;')
row = cursor.fetchone()
while row:
print(str(row[0]))
row = cursor.fetchone()
# Cleanup
# conn.commit()
cursor.close()
conn.close()
print("Done.")
2-2. Sample-02
import pymssql
import logging
################################################################################
class MSSQL(object):
# ==========================================================================
def __init__(self, dbhost, dbport, dbuser, dbpass, dbname, charset, logger):
self.host, self.port, self.user, self.passwd, self.db, self.charset \
= dbhost, dbport, dbuser, dbpass, dbname, charset
self.logger = logger
# for internal
self.is_opened = False
self.conn = None
# ==========================================================================
def open(self):
self.logger.debug('MSSQL.open: trying to open')
try:
self.conn = pymssql.connect(
host=self.host,
user=self.user,
password=self.passwd,
port=self.port,
database=self.db,
charset=self.charset
)
except Exception as err:
logger.error(err)
logger.exception(err)
raise
else:
self.is_opened = True
self.logger.debug('MSSQL.open: opened!')
return self.is_opened
# ==========================================================================
def close(self):
self.logger.debug('MSSQL.open: trying to close')
if self.conn is not None:
self.conn.close()
self.conn = None
self.is_opened = False
self.logger.debug('MSSQL.close: closed!')
# ==========================================================================
def sql_select(self, sql):
self.logger.debug('MSSQL.sql_select: sql=<%s>' % sql)
with self.conn.cursor() as cursor:
cursor.execute(sql)
# num_fields = len(cursor.description)
field_names = [x[0] for x in cursor.description]
# noinspection PyUnusedLocal
field_types = [x[1] for x in cursor.description]
print('%s' % ','.join(field_names))
rows = cursor.fetchall()
for row in rows:
print(str(row[0]))
row = cursor.fetchone()
################################################################################
# 로거 인스턴스 반환
def __get_logger():
__logger = logging.getLogger('logger')
# 로그 포멧 정의
formatter = logging.Formatter(
# '##%(levelname)s##%(asctime)s##@@file::%(filename)s@@line::%(lineno)s >> %(message)s')
'#%(levelname)s##%(asctime)s##@@line::%(lineno)s >> %(message)s')
# 스트림 핸들러 정의
stream_handler = logging.StreamHandler()
# 각 핸들러에 포멧 지정
stream_handler.setFormatter(formatter)
# 로거 인스턴스에 핸들러 삽입
__logger.addHandler(stream_handler)
# 로그 레벨 정의
__logger.setLevel(logging.DEBUG)
return __logger
if __name__ == '__main__':
logger = __get_logger()
MSSQL.__init__(MSSQL, '서버IP', '포트', '아이디', '패스워드', 'DB명', 'utf8', logger)
result = MSSQL.open(MSSQL)
logger.debug(result)
query = 'SELECT @@version;'
MSSQL.sql_select(MSSQL, query)
MSSQL.close(MSSQL)
728x90
'Python' 카테고리의 다른 글
[crawling] Web 이미지 다운로드 (0) | 2021.12.17 |
---|---|
[Ubuntu 20.04] 파이썬 최신 버전(3.9.X) 설치 (0) | 2021.12.14 |
[Python] DB Connection - MySQL (0) | 2021.03.04 |
[Python] DB Connection - ORACLE (0) | 2021.03.04 |
[Python] openpyxl을 이용한 Excel 파일 다루기 (0) | 2021.02.15 |