Python Operations SQL Server sample

Source: Internet
Author: User
Tags sql server example

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.