This article is primarily a python operation SQL Server example, which includes executing queries and updating operations (written in Chinese).
Note that: When reading the data need decode ('utf-8 '), write the data need to encode ('utf-8 '), so as to avoid annoying Chinese garbled or error problems.
Python operations SQL Server requires the Pymssql module to be installed using the PIP install pymssql.
In addition the code used in the package mssql class is searched from the Internet, directly use.
#-*-coding:utf-8-*-ImportpymssqlclassMSSQL:def __init__(self,host,user,pwd,db): Self.host=host Self.user=User Self.pwd=pwd self.db=DBdef __getconnect(self):if notself.db:Raise(Nameerror,"database information not set") Self.conn= Pymssql.connect (host=self.host,user=self.user,password=self.pwd,database=self.db,charset="UTF8") cur=self.conn.cursor ()if notcur:Raise(Nameerror,"failed to connect to database") Else: returncurdefExecQuery (self,sql): cur= self.__getconnect() cur.execute (SQL) Reslist=Cur.fetchall ()#connection must be closed after query is completeself.conn.close ()returnreslistdefexecnonquery (self,sql): cur= self.__getconnect() cur.execute (SQL) Self.conn.commit () Self.conn.close () Ms= MSSQL (host="192.168.1.1", user="SA", pwd="SA", db="TestDB") Reslist= Ms. ExecQuery ("SELECT * from WebUser") forIinchreslist:PrintInewsql="update webuser set name= '%s ' where id=1"%u'Test'PrintNewsqlms. Execnonquery (Newsql.encode ('Utf-8'))
Python Operations SQL Server sample