該項目開發主要使用SQL Server數據庫,但有時候需要用到Python與數據庫交互:查詢數據並導出、往數據庫裏插入數據等操作。以下腳本爲從數據庫裏通過查詢獲取數據,進而導出或存儲等操作。
操作流程如下:
- 首先通過ip,用戶名、密碼、要連接到的數據庫名建立連接。這裏還有一個charset參數需要格外說一下,我之前建立連接的時候並沒有指定該參數,查詢的結果也是沒問題的。但有一次查詢到的結果爲亂碼,發現是編碼方式的問題,故後來就把該參數也添加了進來。該參數一般指定爲GBK即可。
- 建立連接後,就可以開始通過遊標cursor執行sql語句達到我們想要的結果。
- sql語句執行完後,再通過cursor.fetchall獲取數據。
import os, sys
import pymssql
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
CurrentFile = os.path.abspath(__file__)
CurrentPath = os.path.dirname(CurrentFile)
FatherPath = os.path.dirname(CurrentPath)
import configparser
cf = configparser.ConfigParser()
# 出於安全性考慮,這些配置信息都存放到doc下的配置文件裏。
cf.read(os.path.join(FatherPath, 'doc/config.ini'))
mscon_dict = dict(cf.items('mssql-config'))
class MssqlConnect(object):
def __init__(self):
self.host = mscon_dict['host']
self.user = mscon_dict['user']
self.pwd = mscon_dict['pwd']
self.db = mscon_dict['db']
self.charset = mscon_dict['charset']
def query(self, tablename):
logger.info('>>> 開始連接數據庫')
try:
connect = pymssql.connect(host = self.host,
user = self.user,
password = self.pwd,
database = self.db,
charset=self.charset
)
logger.info('>>> 數據庫連接成功')
try:
with connect.cursor() as cursor:
sqlstr_cols = F"SELECT COLUMN_NAME,DATA_TYPE FROM INFORMATION_SCHEMA.columns WHERE TABLE_NAME= '{tablename}'"
cursor.execute(sqlstr_cols)
cols = [col[0] for col in cursor.fetchall()]
cursor.execute(f'select * from {tablename}')
res = cursor.fetchall()
df = pd.DataFrame(res,columns=cols)
except Exception as e:
df = pd.DataFrame()
logger.info(F'>>> 查詢數據失敗,查詢語句爲:{sqlstr};\n錯誤信息爲:{e}')
finally:
connect.close()
except Exception as e:
df = pd.DataFrame()
logger.info('>>> 數據庫連接失敗,請檢查配置信息是否準確。錯誤信息爲:{}'.format(e))
return df
if __name__ == '__main__':
from tabulate import tabulate
tablename = 'STG_END_MAIL_CONF'
t0 = time.time()
df = MssqlConnect().query(tablename)
print(tabulate(df,headers=df.columns))