|
软件环境:
Windows 7 32bit
Python 3.6 Download https://www.python.org/downloads/
默认安装,并添加环境变量,一路Next ....
数据库: SQL Server2008 R2 Sp2 Express
==============================
使用Python Pip包管理工具:
运行cmd命令,切换到Python安装目录,
如:
C:\Program Files\Python36-32\Scripts
进入目录,并执行命令安装Python所需要的包
1 cd C:\Program Files\Python36-32\Scripts
2 easy_install pip
3 pip install pymssql
提示Error,需要 Microsoft Visual C++ 14.0,安装时,系统提示最低需要安装.NEt Framework4.5.1,继续安装之,
下载地址 :http://landinghub.visualstudio.com/visual-cpp-build-tools
继续重复安装SQL Server for Python库的安装 pip install pymssql,安装成功!
===============================================
报错:关于安装pymssql的坑!(Windows下)
安装pymssql模块包:
下载pymssql模块,从http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql找到!
如果不支持 whl包安装,则先安装pip install wheel,安装wheel工具!
===============================================
Python操作SQL Server 查询及更新操作(写入中文)
需要注意的是:读取数据的时候需要decode('utf-8'),写数据的时候需要encode('utf-8'),这样就可以避免烦人的中文乱码或报错问题。
Python操作SQLServer需要使用pymssql模块,使用pip install pymssql安装即可。
此外代码中使用的封装MSSQL类是从网上搜索到的,直接用即可。
1 # -*- coding:utf-8 -*-
2
3 import pymssql
4
5>
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
37 ms = MSSQL(host="192.168.1.1",user="sa",pwd="sa",db="testdb")
38 reslist = ms.ExecQuery("select * from webuser")
39 for i in reslist:
40 print i
41
42 newsql="update webuser set name='%s' where>
43 print newsql
44 ms.ExecNonQuery(newsql.encode('utf-8'))
Python 连接 SQL Server示例,代码如下:
#-*- coding:GBK -*-
import pymssql
print 'Connect to the Datebase....'
conn = pymssql.connect(host='10.0.1.5' ,user='lc0049999' ,password = '',database='drp')
cur = conn.cursor()
if not cur:
raise(NameError,'connect failed')
cur.execute('select * From lrkjqj')
row = cur.fetchone()
print row
while row:
print row[0],row[1]
row = cur.fetchone()
conn.close()
==============================================
补充 Linux下安装 Pymssql数据库连接库
#安装pymssql,经常遇到异常报错,根本原因少一个依赖包,也就是:freetds-devel 坑爹,貌似是没有提示的。
一条龙安装如下:
1 sudo rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
2 yum -y install gcc gcc++ python-devel freetds-devel python-setuptools
3 easy_install pip
4 pip install pymssql mysql
install Over! |
|
|