本文實例講述了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 timeimport pymssql#import decimalclass 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程序設計有所幫助。
新聞熱點
疑難解答