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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM