• 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:Python27Scripts,而且已经将变量C:Python27和C:Python27Scripts配置到环境变量PATH中。

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

     1 import os,pymssql
     2 
     3 server="192.186.1.26
    work"
     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:Python27Scripts下。

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

    需要注意事项:

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

     

    运行命令:

    cmd中使用pip install xxzzz.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

  • 相关阅读:
    多任务顺序执行解决方案
    数码摄影学习总结
    ASP.NET Core与RESTful API 开发实战(二)
    通过三点求圆心程序(二维和三维两种方式),代码为ABB机器人程序,其他语言也适用
    ABB机器人选项611-1 Path Recovery使用记录
    C#刷新chart控件方法及task的启停功能记录
    ABB机器人输送链跟踪问题记录
    有关C#跨线程操作控件的委托方法
    c#get、set属性及类的继承
    正则表达式学习记录
  • 原文地址:https://www.cnblogs.com/yy3b2007com/p/5716102.html
Copyright © 2020-2023  润新知