#coding:utf-8 import pymssql import pdb 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,"沒有設置數據庫信息") try: self.con= pymssql.connect(host='localhost',user= self.user,password=self.pwd,database =self.db,charset='utf8') cur=self.con.cursor() except Exception,e: print Exception,":",e if not cur: print "連接數據庫失敗" else: return cur def ExecQuery(self,sql): cur=self.__GetConnect() cur.execute(sql) resList=cur.fetchall() self.con.close() return resList def ExecNonQuery(self,sql): cur=self.__GetConnect() cur.execute(sql) self.con.commit() self.con.close() def main (): print "enter the main" ms = MSSQL(host=r"localhost",user =r"sa",pwd=r"Syn19920518",db=r"AdventrueWorksLT2008bak") resList=ms.ExecQuery("select * from Table_StaffInfo ") for i in resList: print i raw_input("result...") if __name__=='__main__': print "enter the main" main(
花了好長時間,仍然還差一點調好。主要重現了一下別人的代碼http://www.cnblogs.com/qianlifeng/archive/2012/02/06/2340367.html
未解決的問題:
1.輸出后顯示的u“x1..”等utf-8格式
2.ExecNonQuery方法未測試
得到的經驗:
1.sql 當時半天沒連上,報錯
Traceback (most recent call last): File "C:/Users/smc8236/Desktop/connSqlserver1", line 2, in <module> con=pymssql.connect(host='10.116.5.176',user='sa',password='123456',database='MASTER_CNBJ') File "pymssql.pyx", line 549, in pymssql.connect (pymssql.c:7112) OperationalError: (20017, '\xc4DB-Lib error message 20017, severity 9:\nUnexpected EOF from the server\nDB-Lib error message 20002, severity 9:\nAdaptive Server connection failed\n')
原因charset=‘utf-8’錯誤,應該改成‘utf8’
另外開啟Sql遠程鏈接,但可能沒什么影響
鏈接如下:http://jingyan.baidu.com/article/6c67b1d6ca06f02787bb1ed1.html
2.雖然中文問題沒有解決,但對編碼有大概了解,Unicode屬於通用類型,gbk,utf-8屬於分支。用的時候先decode成unicode再encode成gbk,utf-8
這個文章比較清楚
http://python.jobbole.com/81244/
這個以后再做參考
http://python.jobbole.com/81244/
科普類文章
http://www.cnblogs.com/gavin-num1/p/5170247.html