pymssql examples

来源:http://www.cnblogs.com/kungfupanda/archive/2016/09/14/5870550.html
-Advertisement-
Play Games

http://pymssql.org/en/latest/pymssql_examples.html Example scripts using pymssql module. Basic features (strict DB-API compliance) from os import gete ...


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

Example scripts using pymssql module.

Basic features (strict DB-API compliance)

from os import getenv
import pymssql

server = getenv("PYMSSQL_TEST_SERVER")
user = getenv("PYMSSQL_TEST_USERNAME")
password = getenv("PYMSSQL_TEST_PASSWORD")

conn = pymssql.connect(server, user, password, "tempdb")
cursor = conn.cursor()
cursor.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL
    DROP TABLE persons
CREATE TABLE persons (
    id INT NOT NULL,
    name VARCHAR(100),
    salesrep VARCHAR(100),
    PRIMARY KEY(id)
)
""")
cursor.executemany(
    "INSERT INTO persons VALUES (%d, %s, %s)",
    [(1, 'John Smith', 'John Doe'),
     (2, 'Jane Doe', 'Joe Dog'),
     (3, 'Mike T.', 'Sarah H.')])
# you must call commit() to persist your data if you don't set autocommit to True
conn.commit()

cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
row = cursor.fetchone()
while row:
    print("ID=%d, Name=%s" % (row[0], row[1]))
    row = cursor.fetchone()

conn.close()

Connecting using Windows Authentication

When connecting using Windows Authentication, this is how to combine the database’s hostname and instance name, and the Active Directory/Windows Domain name and the username. This example uses raw strings (r'...') for the strings that contain a backslash.

conn = pymssql.connect(
    host=r'dbhostname\myinstance',
    user=r'companydomain\username',
    password=PASSWORD,
    database='DatabaseOfInterest'
)

Iterating through results

You can also use iterators instead of while loop.

conn = pymssql.connect(server, user, password, "tempdb")
cursor = conn.cursor()
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')

for row in cursor:
    print('row = %r' % (row,))

conn.close()

Note

Iterators are a pymssql extension to the DB-API.

Important note about Cursors

A connection can have only one cursor with an active query at any time. If you have used other Python DBAPI databases, this can lead to surprising results:

c1 = conn.cursor()
c1.execute('SELECT * FROM persons')

c2 = conn.cursor()
c2.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')

print( "all persons" )
print( c1.fetchall() )  # shows result from c2 query!

print( "John Doe" )
print( c2.fetchall() )  # shows no results at all!

In this example, the result printed after "all persons" will be the result of the second query (the list where salesrep='John Doe') and the result printed after “John Doe” will be empty. This happens because the underlying TDS protocol does not have client side cursors. The protocol requires that the client flush the results from the first query before it can begin another query.

(Of course, this is a contrived example, intended to demonstrate the failure mode. Actual use cases that follow this pattern are usually much more complicated.)

Here are two reasonable workarounds to this:

  • Create a second connection. Each connection can have a query in progress, so multiple connections can execute multiple conccurent queries.

  • use the fetchall() method of the cursor to recover all the results before beginning another query:

    c1.execute('SELECT ...')
    c1_list = c1.fetchall()
    
    c2.execute('SELECT ...')
    c2_list = c2.fetchall()
    
    # use c1_list and c2_list here instead of fetching individually from
    # c1 and c2
    

Rows as dictionaries

Rows can be fetched as dictionaries instead of tuples. This allows for accessing columns by name instead of index. Note the as_dict argument.

conn = pymssql.connect(server, user, password, "tempdb")
cursor = conn.cursor(as_dict=True)

cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
for row in cursor:
    print("ID=%d, Name=%s" % (row['id'], row['name']))

conn.close()

Note

The as_dict parameter to cursor() is a pymssql extension to the DB-API.

Using the with statement (context managers)

You can use Python’s with statement with connections and cursors. This frees you from having to explicitly close cursors and connections.

with pymssql.connect(server, user, password, "tempdb") as conn:
    with conn.cursor(as_dict=True) as cursor:
        cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
        for row in cursor:
            print("ID=%d, Name=%s" % (row['id'], row['name']))

Note

The context manager personality of connections and cursor is a pymssql extension to the DB-API.

Calling stored procedures

As of pymssql 2.0.0 stored procedures can be called using the rpc interface of db-lib.

with pymssql.connect(server, user, password, "tempdb") as conn:
    with conn.cursor(as_dict=True) as cursor:
        cursor.execute("""
        CREATE PROCEDURE FindPerson
            @name VARCHAR(100)
        AS BEGIN
            SELECT * FROM persons WHERE name = @name
        END
        """)
        cursor.callproc('FindPerson', ('Jane Doe',))
        for row in cursor:
            print("ID=%d, Name=%s" % (row['id'], row['name']))

Using pymssql with cooperative multi-tasking systems

New in version 2.1.0.

You can use the pymssql.set_wait_callback() function to install a callback function you should write yourself.

This callback can yield to another greenlet, coroutine, etc. For example, for gevent, you could use itsgevent.socket.wait_read() function:

import gevent.socket
import pymssql

def wait_callback(read_fileno):
    gevent.socket.wait_read(read_fileno)

pymssql.set_wait_callback(wait_callback)

The above is useful if you’re say, running a Gunicorn server with the gevent worker. With this callback in place, when you send a query to SQL server and are waiting for a response, you can yield to other greenlets and process other requests. This is super useful when you have high concurrency and/or slow database queries and lets you use less Gunicorn worker processes and still handle high concurrency.

Note

set_wait_callback() is a pymssql extension to the DB-API 2.0.

Next  Previous

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • http://www.cnblogs.com/cookiehu/p/4994278.html 定義異常捕獲類型及處理方法: 這裡面需要註意幾點: a、condition_value [,condition_value],這個的話說明可以包括多種情況(方括弧表示可選的),也就是一個handler可以定 ...
  • http://www.java2s.com/Code/SQL/Cursor/Outputdatainacursor.htm ...
  • MySQL Cursor Summary: in this tutorial, you will learn how to use MySQL cursor in stored procedures to iterate through a result set returned by a SELE ...
  • MDX函數(官方順序) 1. AddCalculatedMembers (MDX) 返回通過將計算成員添加到指定集而生成的集。 語法: AddCalculatedMembers(Set_Expression) 參數: Set_Expression 返回集的有效多維表達式 (MDX)。 預設情況下,M ...
  • 迴圈語句示例 declare v_rlt number(8) := 37; begin loop v_rlt := v_rlt + 1; if v_rlt ...
  • MS SQL Server沒有split()函數,但是我們可以寫一個Table-valued Functions定義函數[dbo].[udf_SplitStringToTable] : CREATE FUNCTION [dbo].[udf_SplitStringToTable] ( @string ...
  • 公司的一個項目,使用的nodejs做服務端,資料庫是postgresql,在本地時一切ok,放在centos時,postgresql配置ok,可以遠程訪問,但是nodejs在centos啟動時,就會報錯,找不到postgresql服務,Error Msg如下: 09/14 10:00:27 - in ...
  • 常見錯誤: ORA-00001:違反唯一約束條件(主鍵錯誤) ORA-00028:無法連接資料庫進程ORA-00900:無效sql語句 ORA-00904:欄位名寫錯或是建表時最後一個欄位有逗號 ORA-00907:缺少右括弧 ORA-00911:無效字元ORA-00917:缺少逗號 ORA-009 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...