Python:安装mssql模块功能,并实现与sqlserver连接、查询

由于我系统是x64系统,所以下载python2.7 x64。下载地址:https://www.python.org/downloads/release/python-2712/,

 


经过测试发现这个版本安装后是自带easy_install、pip、wheel功能的,其他版本或者x86版本中没有改功能。

安装好python后,默认安装在C:\Python27\下,在安装目录下已经包含了easy_install和pip这两个功能在C:\Python27\Scripts,而且已经将变量C:\Python27\和C:\Python27\Scripts配置到环境变量PATH中。

我们要实现这样一个功能,使用python连接sqlserver数据库,并返回当前数据库时间。

 1 import os,pymssql
 2 
 3 server="192.186.1.26\nwork"
 4 user="np"
 5 password="np.123"
 6 
 7 conn=pymssql.connect(server,user,password,database="master")
 8 cursor=conn.cursor()
 9 cursor.execute("""select getdate()""")
10 row=cursor.fetchone()
11 while row:
12     print("sqlserver version:%s"%(row[0]))
13     row=cursor.fetchone()
14 
15 conn.close()

使用的编辑器:“IDLE (Python GUI)”,F5运行代码,第一个错误来了找不到pymssql模块。

问题1:缺少pymssql模块

安装pymssql模块:

下载pymssql模块,从http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql找到:

点击下载,下载后我把“pymssql-2.1.3-cp27-cp27m-win_amd64.whl”文件拷贝到了C:\Python27\Scripts下。

如果当前环境还不支持.whl文件操作,可以使用pip install wheel,安装wheel工具:

需要注意事项:

当没有wheel时,而且又不是联网的情况下,也需要先下载wheelxxxx.whl文件,之后离线安装wheel才可以。下载wheelxxxx.whl文件地址:http://www.lfd.uci.edu/~gohlke/pythonlibs/#wheel

 

运行命令:

cmd中使用pip install xx\zzz.whl

 问题2:连接sqlserver失败

IDLE (Python GUI)中F5运行代码,抛出下边异常:

1 Traceback (most recent call last):
2 File "C:/Users/xx/Desktop/firstPythonStudy.py", line 7, in <module>
3 conn=pymssql.connect(server,user,password,database="master")
4 File "pymssql.pyx", line 644, in pymssql.connect (pymssql.c:10892)
5 InterfaceError: Connection to the database failed for an unknown reason.
6 >>>

 经过搜索终于知道问题,原来是我的server写错了。

正确是这样写的:

 1 server="192.186.1.26\\nwork" 

 修改后F5运行结果:

参考资料:

How to install pymssql on windows with python 2.7?:http://stackoverflow.com/questions/4666290/how-to-install-pymssql-on-windows-with-python-2-7

windows7下怎样安装whl文件(python):http://blog.csdn.net/fhl812432059/article/details/51745226

pymssql examples:http://pymssql.org/en/latest/pymssql_examples.html

posted @ 2016-07-28 20:13  cctext  阅读(34531)  评论(4编辑  收藏  举报