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
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 ...
随机推荐
- node.js1
node的helloworld是非常的简单. 下载node绿色安装包即可.转至node.exe所在目录——写一个hw.js,然后cmd下执行node hw.js——返回相应结果.. http://ww ...
- ASP.NET将原始图片按照指定尺寸等比例缩放显示图片
网站上可能会有很多图片,比如产品图片等,而且他们可能大小不一,宽度和高度也不一定一样,有的很大有的很小.如果放在一张网页上,可能会破坏版面,但是如果强制让他们按照指定的宽度和高度显示,因为比例不同还会 ...
- 知方可补不足~用CDC功能来对数据库变更进行捕捉
回到目录 如果我们希望监视一个数据表的变化,在sql2008之前的版本里,在数据库端可能想到的只有触发器,或者在程序端通过监视自己的insert,update,delete来实现相应的功能,这种实现无 ...
- from表单iframe原网页嵌入
今天是巩固的from表单跟嵌入其他页面,同样的,学习到了新的知识. 温故而知新: iframe--在原页面嵌入其他页面,以窗口的样式 其中scrolling--滚动条 noresize--可调整大小 ...
- JSON和JSONP的区别
先前的概念中对JSON还是比较熟悉,对JSONP不是特别的清楚,整理完相关知识发现才豁然开朗.简单的说JSON是一种数据交换格式,而JSONP是 一种非官方跨域数据交互协议.JSON是“暗号”,而JS ...
- Linux下MakeFile初探
make是linux下的编译命令,用于编译和生成Linux下的可执行文件.这个命令处理的对象是Makefile,makefile等.由于make的强大解析能力,makefile文件的编写也变得极为简单 ...
- Android线程机制——AsyncTask
对于Android为什么要使用多线程,因为从Android4.0之后,谷歌规定了网络操作不允许放在主线程中执行,由此就有了多线程的机制,有个JAVA学习经验的朋友一定知道多线程指的是什么,简单来讲就是 ...
- UTL_FILE
在PL/SQL中,UTL_FILE包提供文本文件输入和输出功能. 可以访问的目录通过初始化参数UTL_FILE_DIR设置. 注意:UTL_FILE只能读取服务器端文本文件,不能读取二进制文件.这时候 ...
- PL/SQL异常处理
As we all known,程序的错误一般分为两类:编译错误和运行时错误.其中运行时错误被称为异常.PL/SQL语句块中处理异常的部分即为异常处理部分.在异常处理部分,可以指定当特定异常发生时所采 ...
- 初探JavaScript(四)——作用域链和声明提前
前言:最近恰逢毕业季,千千万万的学生党开始步入社会,告别象牙塔似的学校生活.往往在人生的各个拐点的时候,情感丰富,感触颇深,各种对过去的美好的总结,对未来的展望.与此同时,也让诸多的老“园”工看完这些 ...