class SqlServer(object):
""" Sql Server db operator. """
def __init__(self, username, password, host, database):
self._conn = pymssql.connect(server=host, user=username, password=password, database=database, charset='utf8',
as_dict=True) # 结果封装成字典,方便获取
self.cursor = self._conn.cursor()
# query methods
def query_all(self, sql) -> list:
self.cursor.execute(sql)
rows = self.cursor.fetchall()
result = []
for row in rows:
result.append({key: self._transcoding(value) for key, value in row.items()})
return result
# 转码一下=========================================================================
def _transcoding(self, v):
if not v:
return v
if not isinstance(v, str):
return v
try:
return v.encode("latin-1", errors="ignore").decode("gbk", errors="ignore")
except Exception:
return v
def query_one(self, sql):
self.cursor.execute(sql)
return self.cursor.fetchone()
def query_by(self, sql, name_params={}):
if len(name_params) > 0:
self.cursor.execute(sql, name_params)
else:
self.cursor.execute(sql)
rows = self.cursor.fetchall()
result = []
for row in rows:
result.append({key: self._transcoding(value) for key, value in row.items()})
return result
def insert_batch(self, sql, name_params=[]):
"""batch insert much rows one time,use location parameter"""
self.cursor.prepare(sql)
self.cursor.executemany(None, name_params)
self.commit()
def commit(self):
self._conn.commit()
def __del__(self):
if hasattr(self, 'cursor'):
self.cursor.close()
if hasattr(self, '_conn'):
self._conn.close()