python-整理--連接MSSQL


環境 : python3.4 / win10 / vs2013 / sqlexpress2014

需要的工具和包

1.freetds包 下載地址 https://github.com/ramiro/freetds/releases

2.openssl包(freetds包要引用到的這個包) 下載地址 http://www.npcglib.org/~stathis/blog/precompiled-openssl/

3.pymssql包 下載地址(不是官網)http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql    或者到CMD里執行 pip install pymssql 

                  下載地址2(官網搜索) https://pypi.python.org/pypi/pymssql/2.1.2

安裝測試:

          前兩個包都下的是編譯好的版本(python3.4對應VS2010,openssl下的是VS2013),解壓之后添加各包的BIN目錄到環境變量

          打開CMD 輸入TSQL tsql -S 127.0.0.1\SQLEXPRESS -U sa -P 123456

           -S 主機和實例名 -U 數據庫賬號 -P 密碼

到此為止,TDS測試連接成功了.

二.pymqql 模塊連接mssql

  這個模塊包含pymssql和_mssql兩個模塊.它們的關系如右圖(來自源碼文件中)

可以使用pymssql這個模塊,也可以使用_mssql.從圖上看,區別是pymssql是在_mssql上作了封裝,是為了遵守python的DBAPI規范接口.

pymssql文檔地址 http://pymssql.org/en/latest/intro.html 

pymssql安裝遇到的問題

pymssql安裝好之后,發生找不到DLL的問題,這些DLL是FREETDS和SSL的DLL庫,將它們放到pymssql的安裝包目錄下就可以了

1.編譯

  源碼下載地址 https://github.com/pymssql/pymssql

      在源碼目錄執行  setup.py build

  如果報錯說找不到VC++10,可以新加一個環境變量 VS100COMNTOOLS  C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\      .要用到C++編譯工具,其實裝了VS2013后這個變量值本來就有,不過名字叫VS12,我安裝的是PYTHON3.4版本,說是對應VS2010的編譯器,所以setup.py文件里會找VS2010的編譯工具路徑,名字叫VS10.

     此時又出錯了,說是link.exe dll/ ....(略)找不到一系列的DLL.經過查找,缺少的就是FREETDS和SSL的庫.此時需要:

    1).在源代碼目錄的freetds目錄下新建目錄vs2010_32,然后將之前下載好的freetds-v0.95.81-win-x86-vs2010里面的libinclude兩個文件夾復制到此.

    2).在源代碼根目錄下新建目錄openssl,然后將之前下載好的openssl-1.0.2f-vs2013里面的lib目錄復制到此

     再次編譯或者直接安裝 setup.py install   ,pymssql會被安裝到python34的lib/site-packages目錄里面,也就是裝第三方模塊的目錄

     到於為什么新建的文件夾是這些名字,可以查看setup.py腳本,里面都有提及.為什么不將這些庫直接包含有源碼里呢,可能是因為這也是三方庫,而且編譯好的版本並不一定適用使用者吧.

2.使用

  安裝之后使用,發現報錯說是找不到DLL模塊.此時將上面1),2)步提到的DLL文件拿出來直接放到pymssql安裝目錄下面就可以了

3.問題

  pip install pymssql 使用這個命令安裝的話,就可能發生找不到DLL模塊的錯誤

  pip install pymssql-2.1.2-cp34-cp34m-win32.whl 使用下載好的WINDOWS離線安裝包,則沒出現這個問題

三 myssql增刪查改示例

  

import _mssql
# 登錄連接超時時間60S 
# Timeout for connection and login in seconds, default 60.
print(_mssql.login_timeout) 

# 從這個錯誤嚴重程序起開始引發異常.默認值6適合大多數情況.
# Minimum severity of errors at which to begin raising exceptions. The default value of 6 should be appropriate in most cases.
print(_mssql.min_error_severity)

# 設置允許在任何給定時間打開的並發連接的最大數目。默認值是25。
# Sets maximum number of simultaneous connections allowed to be open at any given time. Default is 25.
# 這是個方法,加入參數即為設置.此處打印出來的是4096 數據庫版本為SQLEXPRESS2014
print(_mssql.get_max_connections())

#########################################################################################
# 建立連接使用這個對象 _mssql.MSSQLConnection 以下是連接參數
# 可以通過調用pymssql.connect創建這個類的一個實例()。它接受以下參數。請注意,您可以使用關鍵字參數,而不是位置arguments.5。
# server (str) 
    #r'.\SQLEXPRESS' – SQLEXPRESS instance on local machine (Windows only)
    #r'(local)\SQLEXPRESS' – Same as above (Windows only)
    #'SQLHOST' – Default instance at default port (Windows only)
    #'SQLHOST' – Specific instance at specific port set up in freetds.conf (Linux/*nix only)
    #'SQLHOST,1433' – Specified TCP port at specified host
    #'SQLHOST:1433' – The same as above
    #'SQLHOST,5000' – If you have set up an instance to listen on port 5000
    #'SQLHOST:5000' – The same as above
# user (str) – 用戶名 Database user to connect as
# password (str) – 密碼 User’s password
# charset (str) –  字符集的名稱為連接設置。Character set name to set for the connection.
# database (str) – 要初始連接到數據庫中;通過默認,SQL Server的選擇被設置為默認的特定用戶數據庫 The database you want to initially to connect to; by default, SQL Server selects the database which is set as the default for the specific user
# appname (str) – 設置為用於連接的應用程序的名稱 Set the application name to use for the connection
# port (str) – TCP端口用於連接到服務器 the TCP port to use to connect to the server
# tds_version (str) – TDS協議版本索要。默認值:'7.1' TDS protocol version to ask for. Default value: ‘7.1’
# conn_properties – SQL查詢在連接建立時發送到服務器。可以是一個字符串或另一種字符串可迭代的。 默認值: SQL queries to send to the server upon connection establishment. Can be a string or another kind of iterable of strings. Default value:
    #SET ARITHABORT ON;
    #SET CONCAT_NULL_YIELDS_NULL ON;
    #SET ANSI_NULLS ON;
    #SET ANSI_NULL_DFLT_ON ON;
    #SET ANSI_PADDING ON;
    #SET ANSI_WARNINGS ON;
    #SET ANSI_NULL_DFLT_ON ON;
    #SET CURSOR_CLOSE_ON_COMMIT ON;
    #SET QUOTED_IDENTIFIER ON;
    #SET TEXTSIZE 2147483647; -- http://msdn.microsoft.com/en-us/library/aa259190%28v=sql.80%29.aspx

# 建立連接對象
dbconn=_mssql.connect(server=r'.\SQLEXPRESS',user='sa',password='123456',database='testdb',charset='utf8')
# 是否連接狀態
print(dbconn.connected)
# TDS版本MSSQLConnection.tds_version
print(dbconn.tds_version)
# 插入一個語句
re=dbconn.execute_non_query("insert into WuJiang(Name,WuLi,ZhiLi,Sudu,WuPin,ZhiWu) values(%s,%d,%d,%d,%s,%s)",('曹操',215,230,180,'倚天劍','丞相'))
# 影響的行數
print('執行insert后影響的行數:',dbconn.rows_affected)
# 標識值返回
print(dbconn.identity)
# 打印字符集名
print(dbconn.charset)
# 執行一個查詢
dbconn.execute_query('SELECT * FROM WuJiang')
# 這是結果集列表
dblist=[]
# MSSQLConnection類有一個迭帶器,可以進行遍歷.它包含一個類,實現了迭帶器的一些典型方法(可在查看源碼)
for row in dbconn:
    #print("Id={0},Name={1},WuLi={2},ZhiLi={3},Sudu={4},WuPin={5},ZhiWu={6}".format(row['Id'], row['Name'],row['WuLi'],row['ZhiLi'],row['Sudu'],row['WuPin'],row['ZhiWu']))
    dblist.append(row)
from DBA.Model import Model
wjobj=Model()
# dblist中的row,是數據表中的一行,是個字典.對列的一個字段包含兩種鍵值對{列名:值,列索引:值}
for k,v in dblist[0].items():
    if type(k)==str:# 這里只取列名:值 鍵值對
        wjobj.__dict__[k]=v
print(wjobj.__dict__)

# 執行標量查詢
na=dbconn.execute_scalar("select name from wujiang where id=%s",'0')
print(na)

# 得到一個row
ro=dbconn.execute_row("select Name,WuLi,ZhiLi,Sudu,WuPin,ZhiWu,Id from wujiang where id=%d",1)
print(ro)

# 得到列標題
colname=dbconn.get_header()
print(colname)

print()
# 基礎異常
try:
    dbconn.execute_query("select Name,WuLi,ZhiLi,Sudu,WuPin,ZhiWu,Id from wujiang where id=%d",'abc')
except  _mssql.MssqlDatabaseException as e:
    print('此處發生了異常,內容:',e.message)
    #raise    

# 執行刪除
dbconn.execute_non_query("delete wujiang where id>%d",(1))
print('執行delete后影響的行數:',dbconn.rows_affected)

dbconn.close()
View Code 增刪查改示例

 


免責聲明!

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



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