Python實現的連線mssql資料庫操作示例
阿新 • • 發佈:2020-01-09
本文例項講述了Python實現的連線mssql資料庫操作。分享給大家供大家參考,具體如下:
1. 目標資料sql2008 R2 ComPrject=>TestModel
2. 安裝python 連線mssql 模組
執行
pip install pymssql-2.2.0.dev0-cp36-cp36m-win_amd64.whl
執行完畢 檢視是否成功 pip -m list
3. 編寫python 程式碼
import time import pymssql #import decimal class MSSQL: def __init__(self,host,user,pwd,db): self.host=host self.user=user self.pwd=pwd self.db=db def GetConnect(self): if not self.db: raise(NameError,'沒有目標資料庫') self.connect=pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset='utf8') cur=self.connect.cursor() if not cur: raise(NameError,'資料庫訪問失敗') else: return cur def ExecSql(self,sql): cur=self.GetConnect() cur.execute(sql) self.connect.commit() self.connect.close() def ExecQuery(self,sql): cur=self.GetConnect() cur.execute(sql) resList = cur.fetchall() self.connect.close() return resList def main(): ms = MSSQL(host="192.168.0.108",user="sa",pwd="sa",db="ComPrject") resList = ms.ExecQuery("select *from TestModel") print(resList) if __name__ == '__main__': main() input("執行完成:")
4. 執行效果
備註:如果讀取中文出現亂碼,需要修改varchar=>nvarchar
更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python常見資料庫操作技巧彙總》、《Python編碼操作技巧總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》
希望本文所述對大家Python程式設計有所幫助。