#coding=utf-8 #!/usr/bin/env python #------------------------------------------------------------------------------- # Name: pymssqlTest.py # Purpose: 測試 pymssql庫,該庫到這裏下載:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql # # Author: scott # # Created: 04/02/2012 #------------------------------------------------------------------------------- import pymssql class MSSQL: """ 對pymssql的簡單封裝 pymssql庫,該庫到這裏下載:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql 使用該庫時,須要在Sql Server Configuration Manager裏面將TCP/IP協議開啓 用法: """ def __init__(self,host,user,pwd,db): self.host = host self.user = user self.pwd = pwd self.db = db def __GetConnect(self): """ 獲得鏈接信息 返回: conn.cursor() """ if not self.db: raise(NameError,"沒有設置數據庫信息") self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8") cur = self.conn.cursor() if not cur: raise(NameError,"鏈接數據庫失敗") else: return cur def ExecQuery(self,sql): """ 執行查詢語句 返回的是一個包含tuple的list,list的元素是記錄行,tuple的元素是每行記錄的字段 調用示例: ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics") resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser") for (id,NickName) in resList: print str(id),NickName """ cur = self.__GetConnect() cur.execute(sql) resList = cur.fetchall() #查詢完畢後必須關閉鏈接 self.conn.close() return resList def ExecNonQuery(self,sql): """ 執行非查詢語句 調用示例: cur = self.__GetConnect() cur.execute(sql) self.conn.commit() self.conn.close() """ cur = self.__GetConnect() cur.execute(sql) self.conn.commit() self.conn.close() def main(): ## ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics") ## #返回的是一個包含tuple的list,list的元素是記錄行,tuple的元素是每行記錄的字段 ## ms.ExecNonQuery("insert into WeiBoUser values('2','3')") ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics") resList = ms.ExecQuery("SELECT id,weibocontent FROM WeiBo") for (id,weibocontent) in resList: print str(weibocontent).decode("utf8") if __name__ == '__main__': main()
注意事項:python
使用pymssql進行中文操做時候可能會出現中文亂碼,我解決的方案是:sql
文件頭加上 #coding=utf8數據庫
sql語句中有中文的時候進行encode測試
insertSql = "insert into WeiBo([UserId],[WeiBoContent],[PublishDate]) values(1,'測試','2012/2/1')".encode("utf8")fetch
鏈接的時候加入charset設置信息spa
pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")code