#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