python通过pymssql链接SQL Server

来源:互联网 发布:计算器java编程代码 编辑:程序博客网 时间:2024/06/08 18:06

转自:http://lovesoo.org/python-example-sqlserver.html


本文主要是Python操作SQLServer示例,包括执行查询更新操作(写入中文)。

需要注意的是:读取数据的时候需要decode('utf-8'),写数据的时候需要encode('utf-8'),这样就可以避免烦人的中文乱码或报错问题。

Python操作SQLServer需要使用pymssql模块,使用pip install pymssql安装即可。

此外代码中使用的封装MSSQL类是从网上搜索到的,直接用即可。 

1# -*- coding:utf-8 -*-
2 
3import pymssql
4 
5class MSSQL:
6    def __init__(self,host,user,pwd,db):
7        self.host = host
8        self.user = user
9        self.pwd = pwd
10        self.db = db
11 
12    def __GetConnect(self):
13        if not self.db:
14            raise(NameError,"没有设置数据库信息")
15        self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
16        cur = self.conn.cursor()
17        if not cur:
18            raise(NameError,"连接数据库失败")
19        else:
20            return cur
21 
22    def ExecQuery(self,sql):
23        cur = self.__GetConnect()
24        cur.execute(sql)
25        resList = cur.fetchall()
26 
27        #查询完毕后必须关闭连接
28        self.conn.close()
29        return resList
30 
31    def ExecNonQuery(self,sql):
32        cur = self.__GetConnect()
33        cur.execute(sql)
34        self.conn.commit()
35        self.conn.close()
36 
37ms = MSSQL(host="192.168.1.1",user="sa",pwd="sa",db="testdb")
38reslist = ms.ExecQuery("select * from webuser")
39for i in reslist:
40    print i
41 
42newsql="update webuser set name='%s' where id=1"%u'测试'
43print newsql
44ms.ExecNonQuery(newsql.encode('utf-8'))
0 0
原创粉丝点击