Python連接MSSQL?
Python 想要和MSSql數據庫進行交互,首先要下載名為"pyMSSQL"的包,然后import該包
Python實現連接mssql數據庫,并做簡單的操作:查詢和非查詢操作,代碼如下:
#!usr/bin/python
# -*- coding:utf-8 -*-
import pymssql
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,"no ")
# 打開數據庫連接
self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
# 使用cursor()方法獲取操作游標
cur = self.conn.cursor()
if not cur:
raise(NameError,"connect database fails")
else:
return cur
def ExecQuery(self,sql):
try:
cur = self.__GetConnect()
# 執行SQL語句
cur.execute(sql)
# 獲取所有記錄列表
rows = cur.fetchall()
cur.close()
# 關閉數據庫連接
self.conn.close()
return rows
except:
print "Error: unable to fecth data"
def ExecNonQuery(self,sql):
try:
cur = self.__GetConnect()
cur.execute(sql)
# 提交到數據庫執行
self.conn.commit()
self.conn.close()
except:
# 發生錯誤時回滾
db.rollback()
if __name__ == "__main__":
ms = MSSQL(host="localhost",user="sa",pwd="sasa",db="dbname")
rows = ms.ExecQuery("select * from T_EMP")
for i in rows:
print i
使用的開發工具為pycharm社區版,運行上面的代碼,老是通不過,按照提示的錯誤在網上查找解決辦法,試了不少問題以依舊;最后將開發工具pycharm換成專業版的,上面的代碼就能順利運行了。