pymssql examples
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
- c1.execute('SELECT ...')
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.
pymssql examples的更多相关文章
- pymssql文档(转)
pymssql methods set_max_connections(number) -- Sets maximum number of simultaneous database connecti ...
- Python:安装mssql模块功能,并实现与sqlserver连接、查询
由于我系统是x64系统,所以下载python2.7 x64.下载地址:https://www.python.org/downloads/release/python-2712/, 经过测试发现这个版本 ...
- pymssql文档
原文地址 http://pymssql.org/en/latest/ref/_mssql.html _mssql module reference pymssql模块类,方法和属性的完整文档. Com ...
- Js: Extensible Calendar Examples
http://ext.ensible.comhttps://github.com/bmoeskau/Extensiblehttps://github.com/TeamupCom/extensibleh ...
- python 使用pymssql连接sql server数据库
python 使用pymssql连接sql server数据库 #coding=utf-8 #!/usr/bin/env python#------------------------------ ...
- Selenium Xpath Tutorials - Identifying xpath for element with examples to use in selenium
Xpath in selenium is close to must required. XPath is element locator and you need to provide xpath ...
- https://github.com/chenghuige/tensorflow-exp/blob/master/examples/sparse-tensor-classification/
https://github.com/chenghuige/tensorflow-exp/blob/master/examples/sparse-tensor-classification/ ...
- 为Python安装pymssql模块来连接SQLServer
1.安装依赖包 yum install -y gcc python-devel 2.安装freetds 下载地址:http://pan.baidu.com/s/1pLKtFBl tar zxvf fr ...
- (转载)SQL Reporting Services (Expression Examples)
https://msdn.microsoft.com/en-us/library/ms157328(v=SQL.100).aspx Expressions are used frequently in ...
随机推荐
- SDN跟网络虚拟化的完美结合
SDN跟网络虚拟化的完美结合 之前说过,所谓的“SDN最适合的领域是数据中心”的说法,笔者认为更准确的说法应该是SDN最适合的领域是数据中心中的网络虚拟化应用.为什么说SDN 非常适合用在网络虚拟化中 ...
- ui-router带参数的路由配置
ui-router带参数的路由配置 使用ng-route的时候带参数的连接这样配置: $routeProvider.when('item/itemid/:itemid', { templateUrl: ...
- Liferay7 BPM门户开发之40: Form表单的Action到Render的数据传递
在Form提交后的变量,很多情况是要展现在jsp页面中,这时Action到Render的变量传递就非常有用. 例如,您在数据库中添加了学生的详细信息. 为了实现这一需求,先创建Form表单(学生的细节 ...
- Spring注意事项(各部分理解)
(1),每一个bean属性,就是一个普通的java类. 类有属性,有方法,如何交给容器管理.(注解的方式,xml方式配置) (2),通过Bean来实例化对象的方式 1.通过构造器(一般是无参的默认构造 ...
- poj1062昂贵的聘礼(Dijkstra**)
/* 题意: 物主有一个物品,价值为P,地位为L, 以及一系列的替代品Ti和该替代品所对应的"优惠"Vi g[u][i] 表示的是u物品被i物品替换后的优惠价格!(u>0, ...
- 整理的一些PHP面试题目
1.strlen()和mb_strlen()的作用分别是什么? strlen()和mb_strlen()的作用都是来获取字符串的长度,其中strlen()只针对单字节编码字符,也就是计算字符串的总字节 ...
- [java] 汇率换算器实现-插曲1-正则表达式(1)
[java] 汇率换算器实现-插曲1-正则表达式(1) // */ // ]]> // */ // ]]> [java] 汇率换算器实现-插曲1-正则表达式(1) Table of C ...
- Windows Azure Virtual Network (5) 设置Azure Virtual Machine固定Private IP
<Windows Azure Platform 系列文章目录> 注意:本文介绍的是Global Azure (http://www.windowsazure.com),如果你使用的是由世纪 ...
- 【原创】Django-ORM基础
概述 1.什么是ORM? ORM,即Object-Relational Mapping(对象关系映射),它的作用是在关系型数据库和业务实体对象之间作一个映射,这样,我们在具体的操作业务对象的时候,就不 ...
- JPG渐进 & PNG/PNG24 交错测试
今天由同事说起,PS导出PNG时,有个选项"交错"是干啥的,想起这也是个问题,所以特意搞了个测试页面: 引用网上"交错-就是类似旧式电视的隔行扫描,让图片只花50%的时间 ...