Pymssql
Pymssql
Pymssql
Release 2.2.0.dev
pymssql developers
1 Introduction 1
1.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Supported related software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Project Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.6 Project Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.7 Current Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 pymssql examples 5
2.1 Basic features (strict DB-API compliance) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Connecting using Windows Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 Iterating through results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 Important note about Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.5 Rows as dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.6 Using the with statement (context managers) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.7 Calling stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.8 Using pymssql with cooperative multi-tasking systems . . . . . . . . . . . . . . . . . . . . . . . . . 8
3 _mssql examples 9
3.1 Quickstart usage of various features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2 An example of exception handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.3 Custom message handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4 Release notes 13
4.1 pymssql 2.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5 FreeTDS 15
5.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.2 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
i
7 _mssql module reference 27
7.1 Module-level symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
7.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
7.3 MSSQLConnection class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
7.4 MSSQLStoredProcedure class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
7.5 Module-level exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
13 Docker 53
14 Change log 55
15 TODO 73
15.1 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
ii
CHAPTER 1
Introduction
it will fetch the package from the Python Package Index (PyPI) and install it.
Note: The statically-linked FreeTDS version bundled with our official pymssql Linux Wheel package doesn’t
have SSL support so it can’t be used to connect to Azure. Also it doesn’t have Kerberos support so it can’t be
used to perform domain logins to SQL Server.
• Mac OS X
(with Homebrew):
Run:
it will fetch the source distribution from the Python Package Index (PyPI), build and install pymssql.
1
pymssql Documentation, Release 2.2.0.dev
• Windows
First make sure you are using pip version 6.0 or newer so you can take advantage of its support for Windows
binary Wheel packages. Starting with pymssql version 2.1.3 we provide such wheel packages that bundle a
static copy of FreeTDS so no additional download or compilation steps are necessary.
Then run:
it will fetch the package from the Python Package Index (PyPI) and install it.
Note: The statically-linked FreeTDS version bundled with our official pymssql Windows Wheel package
doesn’t have SSL support so it can’t be used to connect to Azure.
1.2 Architecture
2 Chapter 1. Introduction
pymssql Documentation, Release 2.2.0.dev
And, as of version 2.1.x it uses the services of the db-lib component of FreeTDS. See the relevant FreeTDS docu-
mentation for additional details.
1.4 Install
1.4.1 pip
Discussions and support take place on pymssql mailing list here: http://groups.google.com/group/pymssql, you can
participate via web, e-mail or read-only subscribing to the mailing list feeds.
This is the best place to get help, please feel free to drop by and ask a question.
Current release: 2.x is the branch under current development. It is a complete rewrite using Cython and the latest
FreeTDS libraries (which remove many of the limitations of previous versions of FreeTDS).
Legacy release: 1.0.3 is the legacy version and is no longer under active development.
Official development repositories and issue trackers have been moved to GitHub at https://github.com/pymssql/
pymssql.
We would be happy to have:
• A couple more developers
• Help from the community with maintenance of this documentation.
If interested, please connect with us on the mailing list.
4 Chapter 1. Introduction
CHAPTER 2
pymssql examples
server = getenv("PYMSSQL_TEST_SERVER")
user = getenv("PYMSSQL_TEST_USERNAME")
password = getenv("PYMSSQL_TEST_PASSWORD")
5
pymssql Documentation, Release 2.2.0.dev
conn.close()
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'
)
conn.close()
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')
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 under-
lying 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()
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.close()
You can use Python’s with statement with connections and cursors. This frees you from having to explicitly close
cursors and connections.
Note: The context manager personality of connections and cursor is a pymssql extension to the DB-API.
As of pymssql 2.0.0 stored procedures can be called using the rpc interface of db-lib.
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.
_mssql examples
import _mssql
conn = _mssql.connect(server='SQL01', user='user', password='password', \
database='mydatabase')
conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))')
conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')")
conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')")
New in version 2.1.0: Iterating over query results by iterating over the connection object just like it’s already possible
with pymssql connections is new in 2.1.0.
9
pymssql Documentation, Release 2.2.0.dev
conn.close()
Please note the usage of iterators and ability to access results by column name. Also please note that parameters to
connect method have different names than in pymssql module.
import _mssql
import _mssql
Release notes
This is a new major version of pymssql. It is totally rewritten from scratch in Cython. Our goals for this version were
to:
• Provide support for Python 3.0 and newer,
• Implement support for stored procedures,
• Rewrite DB-API compilant pymssql module in C (actually in Cython) for increased performance,
• Clean up the module API and the code.
That’s why we decided to bump major version number. Unfortunately new version introduces incompatible changes
in API. Existing scripts may not work with it, and you’ll have to audit them. If you care about compatibility, just
continue using pymssql 1.0.x and slowly move to 2.0.
Project hosting has also changed. Now pymssql is developed on GitHub: http://github.com/pymssql/pymssql.
Credits for the release go to:
• Marc Abramowitz <msabramo_at_gmail_com> who joined the project in Jan 2013 and is responsible for the
actual release of the 2.0 version by fixing many old tickets, coding the port to Python 3 and driving the migration
to Git and GitHub.
• Randy Syring who converted the repository to Mercurial, extended tests and ported them to nose, enhanced the
code in several fronts like multi-platform (compilers, OSes) compatibility, error handling, support of new data
types, SQLAlchemy compatibility and expanded the documentation.
• Damien Churchill <damoxc_at_gmail_com> who set the foundations of the new Cython-based code base, re-
lease engineering, new site features like Sphinx, SimpleJSON and others,
• Andrzej Kukuła <akukula_at_gmail_com> who did all the docs, site migration, and other boring but necessary
stuff.
13
pymssql Documentation, Release 2.2.0.dev
• Jooncheol Park <jooncheol_at_gmail_com> who did develop the initial version of pymssql (until 0.5.2). Now
just doing boring translation docs for Korean.
• Rewritten from scratch in C, you should observe even better performance than before
• dsn parameter to pymssql.connect() has been removed
• host parameter to pymssql.connect() has been renamed to server to be consistent with _mssql
module
• max_conn parameter to pymssql.connect() has been removed
Connection class
Cursor class
• fetchone_asdict() method has been removed. Just use pymssql.connect() with as_dict=True,
then use regular fetchone()
• fetchmany_asdict() method has been removed. Just use pymssql.connect() with
as_dict=True, then use regular fetchmany()
• fetchall_asdict() method has been removed. Just use pymssql.connect() with as_dict=True,
then use regular fetchall()
MSSQLConnection class
FreeTDS
5.1 Installation
5.1.1 Linux
On Linux you can choose between (for the two former choices, when you start the the pymssql installation process it
will look for and pick the header files and libraries for FreeTDS in some usual system-wide locations):
• Use the FreeTDS installation provided by the packages/ports system.
• Build it and install yourself.
• Use the bundled static FreeTDS libraries:
export PYMSSQL_BUILD_WITH_BUNDLED_FREETDS=1
pip install pymssql
These static libraries are built on a x86_64 Ubuntu 14.04 system by using the following sequence:
or
and then:
./configure --enable-msdblib \
--prefix=/usr --sysconfdir=/etc/freetds --with-tdsver=7.1 \
--disable-apps --disable-server --disable-pool --disable-odbc \
--with-openssl=no --with-gnutls=no
make
Changed in version 2.1.3: Version of FreeTDS Linux static libraries bundled with pymssql is 0.95.95.
15
pymssql Documentation, Release 2.2.0.dev
Changed in version 2.1.2: Version of FreeTDS Linux static libraries bundled with pymssql is 0.95.81 obtained
from branch Branch-0_95 of the official Git repository. Up to 2.1.1 the version of FreeTDS bundled was 0.91.
5.1.3 Windows
You can:
1. Simply use our official Wheels which include FreeTDS statically linked and have no SSL support.
2. Build pymssql yourself. In this case you have the following choices regarding FreeTDS:
• Use binaries we maintain at https://github.com/ramiro/freetds/releases
Choose the .zip file appropriate for your architecture (x86 vs. x86_64) and your Python version
(vs2008 for Python 2.7, vs2010 for Python 3.3 and 3.4, vs2015 for Python 3.5 and 3.6).
Those builds include iconv support (via win-iconv statically linked).
They provide both static and dynamic library versions of FreeTDS and versions built both with and without
SSL support via OpenSSL (only dinamically linked).
To install OpenSSL you’ll need the distribution that can be downloaded from http://www.npcglib.org/
~stathis/blog/precompiled-openssl/. Choose the right .7z file for your Python version (vs2008 for Python
2.7, vs2010 for Python 3.3 and 3.4, vs2015 for Python 3.5 and 3.6).
• Or you can build it yourself.
Changed in version 2.1.3: FreeTDS is linked statically again on our official Windows binaries.
pymssql version 2.1.2 included a change in the official Windows Wheels by which FreeTDS was dinamically linked.
Read the relevant change log entry for the rationale behind that decision.
Given the fact this didn’t have a good reception from our users, this change has been undone in 2.1.3, FreeTDS is
statically linked like it happened until version 2.1.1.
5.2 Configuration
pymssql uses FreeTDS package to connect to SQL Server instances. You have to tell it how to find your database
servers. The most basic info is host name, port number, and protocol version to use.
The system-wide FreeTDS configuration file is /etc/freetds.conf or C:\freetds.conf, depending upon
your system. It is also possible to use a user specific configuration file, which is $HOME/.freetds.conf on Linux
and %APPDATA%\.freetds.conf on Windows. Suggested contents to start with is at least:
[global]
port = 1433
tds version = 7.0
With this config you will be able to enter just the hostname to pymssql.connect() and _mssql.connect():
import pymssql
connection = pymssql.connect(server='mydbserver', ...)
16 Chapter 5. FreeTDS
pymssql Documentation, Release 2.2.0.dev
To connect to instance other than the default, you have to know either the instance name or port number on which the
instance listens:
Please see also the pymssql module reference, _mssql module reference, and FAQ pages.
For more information on configuring FreeTDS please go to http://www.freetds.org/userguide/freetdsconf.htm
If you’re sure that your server is reachable, but pymssql for some reason don’t let you connect, you can check the
connection with tsql utility which is part of FreeTDS package:
$ tsql
Usage: tsql [-S <server> | -H <hostname> -p <port>] -U <username> [-P <password>] [-
˓→I <config file>] [-o <options>] [-t delim] [-r delim] [-D database]
(...)
$ tsql -S mydbserver -U user
Note: Use the above form if and only if you specified server alias for mydbserver in freetds.conf. Otherwise use the
host/port notation:
You’ll be prompted for a password and if the connection succeeds, you’ll see the SQL prompt:
1>
You can then enter queries and terminate the session with exit.
If the connection fails, tsql utility will display appropriate message.
5.2. Configuration 17
pymssql Documentation, Release 2.2.0.dev
18 Chapter 5. FreeTDS
CHAPTER 6
pymssql.__version__
pymssql version as an Unicode constant. E.g. u"2.1.1", u"2.2.0"
pymssql.VERSION
pymssql version in tuple form which is more easily handled (parse, compare) programmatically. E.g. (2, 1,
1), (2, 2, 0)
New in version 2.2.0.
pymssql.__full_version__
pymssql version as an Unicode constant but including any (PEP 440) suffixes. E.g. u"2.1.0.dev2", u"2.
2.0.dev"
Constants, required by the DB-API 2.0 specification:
pymssql.apilevel
'2.0' – pymssql strives for compliance with DB-API 2.0.
pymssql.paramstyle
'pyformat' – pymssql uses extended python format codes.
pymssql.threadsafety
1 – Module may be shared, but not connections.
19
pymssql Documentation, Release 2.2.0.dev
6.2 Functions
Warning: Currently, setting timeout or login_timeout has a process-wide effect because the FreeTDS db-lib
API functions used to implement such timeouts have a global effect.
Warning: The tds_version parameter has a default value of None. This means two things:
1. You can’t rely anymore in the old '7.1' default value and
2. Now you’ll need to either
This might look cumbersome but at the same time means you can now fully configure the characteristics of a
connection to SQL Server from Python code when using pymssql without using a stanza for the server in the
freetds.conf file or even with no freetds.conf at all. Up to version 2.1.1 it simply wasn’t possible
to control the TDS protocol version, and in version 2.1.2 it was possible to set it but version 7.1 was used if
not specified.
Warning: FreeTDS added sopport for TDS protocol version 7.3 in version 0.95. You need to be careful of
not asking for TDS 7.3 if you know the undelying FreeTDS used by pymssql is version 0.91 as it won’t raise
any error nor keep you from passing such an invalid value.
pymssql.get_dbversion()
Wrapper around DB-Library’s dbversion() function which returns the version of FreeTDS (actually the
version of DB-Lib) in string form. E.g. "freetds v0.95".
Unfortunately 1) The value returned doesn’t indicate minor revisions (e.g. v0.95.50), 2) Its data type makes
it harder to compare versions or handle it programmatically in other ways and 3) It hasn’t been consistently
updated through the FreeTDS release history.
A pymssql extension to the DB-API 2.0.
pymssql.set_max_connections(number)
Sets maximum number of simultaneous database connections allowed to be open at any given time. Default is
25.
A pymssql extension to the DB-API 2.0.
pymssql.get_max_connections()
Gets current maximum number of simultaneous database connections allowed to be open at any given time.
A pymssql extension to the DB-API 2.0.
pymssql.set_wait_callback(wait_callback_callable)
New in version 2.1.0.
Allows pymssql to be used along cooperative multi-tasking systems and have it call a callback when it’s waiting
for a response from the server.
The passed callback callable should receive one argument: The file descriptor/handle of the network socket
connected to the server, so its signature must be:
def wait_callback_callable(read_fileno):
#...
pass
Its body should invoke the appropiate API of the multi-tasking framework you are using use that results in the
current greenlet yielding the CPU to its siblings whilst there isn’t incoming data in the socket.
See the pymssql examples document for a more concrete example.
A pymssql extension to the DB-API 2.0.
6.2. Functions 21
pymssql Documentation, Release 2.2.0.dev
Connection.autocommit(status)
Where status is a boolean value. This method turns autocommit mode on or off.
By default, autocommit mode is off, what means every transaction must be explicitly committed if changed data
is to be persisted in the database.
You can turn autocommit mode on, what means every single operation commits itself as soon as it succeeds.
A pymssql extension to the DB-API 2.0.
Connection.close()
Close the connection.
Connection.cursor()
Return a cursor object, that can be used to make queries and fetch results from the database.
Connection.commit()
Commit current transaction. You must call this method to persist your data if you leave autocommit at its default
value, which is False.
See also pymssql examples.
Connection.rollback()
Roll back current transaction.
Cursor.rowcount
Returns number of rows affected by last operation. In case of SELECT statements it returns meaningful infor-
mation only after all rows have been fetched.
Cursor.connection
This is the extension of the DB-API specification. Returns a reference to the connection object on which the
cursor was created.
Cursor.lastrowid
This is the extension of the DB-API specification. Returns identity value of last inserted row. If previous
operation did not involve inserting a row into a table with identity column, None is returned.
Cursor.rownumber
This is the extension of the DB-API specification. Returns current 0-based index of the cursor in the result set.
Cursor.close()
Close the cursor. The cursor is unusable from this point.
Cursor.execute(operation)
Cursor.execute(operation, params)
operation is a string and params, if specified, is a simple value, a tuple, a dict, or None.
Performs the operation against the database, possibly replacing parameter placeholders with provided values.
This should be preferred method of creating SQL commands, instead of concatenating strings manually, what
makes a potential of SQL Injection attacks. This method accepts formatting similar to Python’s builtin string
interpolation operator. However, since formatting and type conversion is handled internally, only the %s and %d
placeholders are supported. Both placeholders are functionally equivalent.
Keyed placeholders are supported if you provide a dict for params.
If you call execute() with one argument, the % sign loses its special meaning, so you can use it as usual in
your query string, for example in LIKE operator. See the examples.
You must call Connection.commit() after execute() or your data will not be persisted in the database.
You can also set connection.autocommit if you want it to be done automatically. This behaviour is
required by DB-API, if you don’t like it, just use the _mssql module instead.
Cursor.executemany(operation, params_seq)
operation is a string and params_seq is a sequence of tuples (e.g. a list). Execute a database operation repeatedly
for each element in parameter sequence.
Cursor.fetchone()
Fetch the next row of a query result, returning a tuple, or a dictionary if as_dict was passed to pymssql.
connect(), or None if no more data is available. Raises OperationalError (PEP 249#operationaler-
ror) if previous call to execute*() did not produce any result set or no call was issued yet.
Cursor.fetchmany(size=None)
Fetch the next batch of rows of a query result, returning a list of tuples, or a list of dictionaries if as_dict was
passed to pymssql.connect(), or an empty list if no more data is available. You can adjust the batch size
using the size parameter, which is preserved across many calls to this method. Raises OperationalError
(PEP 249#operationalerror) if previous call to execute*() did not produce any result set or no call was
issued yet.
Cursor.fetchall()
Fetch all remaining rows of a query result, returning a list of tuples, or a list of dictionaries if as_dict was passed
to pymssql.connect(), or an empty list if no more data is available. Raises OperationalError (PEP
249#operationalerror) if previous call to execute*() did not produce any result set or no call was issued
yet.
Cursor.nextset()
This method makes the cursor skip to the next available result set, discarding any remaining rows from the
current set. Returns True value if next result is available, None if not.
Cursor.__iter__()
Cursor.next()
These methods facilitate Python iterator protocol. You most likely will not call them directly, but indirectly by
using iterators.
A pymssql extension to the DB-API 2.0.
Cursor.setinputsizes()
Cursor.setoutputsize()
These methods do nothing, as permitted by DB-API specs.
6.5 Exceptions
exception pymssql.StandardError
Root of the exception hierarchy.
exception pymssql.Warning
Raised for important warnings like data truncations while inserting, etc. A subclass of StandardError.
exception pymssql.Error
Base class of all other error exceptions. You can use this to catch all errors with one single except statement. A
subclass of StandardError.
exception pymssql.InterfaceError
Raised for errors that are related to the database interface rather than the database itself. A subclass of Error.
exception pymssql.DatabaseError
Raised for errors that are related to the database. A subclass of Error.
exception pymssql.DataError
Raised for errors that are due to problems with the processed data like division by zero, numeric value out of
range, etc. A subclass of DatabaseError.
exception pymssql.OperationalError
Raised for errors that are related to the database’s operation and not necessarily under the control of the pro-
grammer, e.g. an unexpected disconnect occurs, the data source name is not found, a transaction could not be
processed, a memory allocation error occurred during processing, etc. A subclass of DatabaseError.
exception pymssql.IntegrityError
Raised when the relational integrity of the database is affected, e.g. a foreign key check fails. A subclass of
DatabaseError.
exception pymssql.InternalError
Raised when the database encounters an internal error, e.g. the cursor is not valid anymore, the transaction is
out of sync, etc. A subclass of DatabaseError.
exception pymssql.ProgrammingError
Raised for programming errors, e.g. table not found or already exists, syntax error in the SQL statement, wrong
number of parameters specified, etc. A subclass of DatabaseError.
exception pymssql.NotSupportedError
Raised in case a method or database API was used which is not supported by the database, e.g. requesting a
rollback() on a connection that does not support transaction or has transactions turned off. A subclass of
DatabaseError.
exception pymssql.ColumnsWithoutNamesError
Raised by Cursor.execute() when as_dict=True has been specified to open the connection and
the query sent to the server doesn’t involve columns names in its results. A subclass of InterfaceError.
6.5. Exceptions 25
pymssql Documentation, Release 2.2.0.dev
_mssql.__version__
See pymssql.__version__.
_mssql.VERSION
See pymssql.VERSION .
New in version 2.2.0.
_mssql.__full_version__
See pymssql.__full_version__.
Variables whose values you can change to alter behavior on a global basis:
_mssql.login_timeout
Timeout for connection and login in seconds, default 60.
_mssql.min_error_severity
Minimum severity of errors at which to begin raising exceptions. The default value of 6 should be appropriate
in most cases.
7.2 Functions
_mssql.set_max_connections(number)
Sets maximum number of simultaneous connections allowed to be open at any given time. Default is 25.
_mssql.get_max_connections()
Gets current maximum number of simultaneous connections allowed to be open at any given time.
27
pymssql Documentation, Release 2.2.0.dev
class _mssql.MSSQLConnection
This class represents an MS SQL database connection. You can make queries and obtain results through a
database connection.
You can create an instance of this class by calling _mssql.connect(). It accepts the following arguments.
Note that you can use keyword arguments, instead of positional arguments.
Parameters
• server (str) – Database server and instance you want to connect to. Valid examples are:
– 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) – 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) – the TCP port to use to connect to the server
• tds_version (str) – TDS protocol version to ask for. Default value: None
• conn_properties – SQL queries to send to the server upon connection establishment.
Can be a string or another kind of iterable of strings. Default value:
Warning: The tds_version parameter has a default value of None. This means two things:
1. You can’t rely anymore in the old '7.1' default value and
2. Now you’ll need to either
This might look cumbersome but at the same time means you can now fully configure the characteristics
of a connection to SQL Server when using pymssql/_mssql without using a stanza for the server in the
freetds.conf file or even with no freetds.conf at all. Starting with pymssql version 2.0.0 and up
to version 2.1.2 it was already possible to set the TDS protocol version to ask for when connecting to the
server but version 7.1 was used if not specified.
Warning: FreeTDS added sopport for TDS protocol version 7.3 in version 0.95. You need to be careful of
not asking for TDS 7.3 if you know the undelying FreeTDS used by pymssql is version 0.91 as it won’t raise
any error nor keep you from passing such an invalid value.
MSSQLConnection.connected
True if the connection object has an open connection to a database, False otherwise.
MSSQLConnection.charset
Character set name that was passed to _mssql.connect().
MSSQLConnection.identity
Returns identity value of last inserted row. If previous operation did not involve inserting a row into a table with
identity column, None is returned. Example usage – assume that persons table contains an identity column in
addition to name column:
MSSQLConnection.query_timeout
Query timeout in seconds, default is 0, which means to wait indefinitely for results. Due to the way DB-
Library for C works, setting this property affects all connections opened from the current Python script (or, very
technically, all connections made from this instance of dbinit()).
MSSQLConnection.rows_affected
Number of rows affected by last query. For SELECT statements this value is only meaningful after reading all
rows.
MSSQLConnection.debug_queries
If set to true, all queries are printed to stderr after formatting and quoting, just before being sent to SQL Server.
It may be helpful if you suspect problems with formatting or quoting.
MSSQLConnection.tds_version
The TDS version used by this connection. Can be one of 4.2, 5.0 7.0, 7.1, 7.2, 7.3 or None if no TDS
version could be detected.
Changed in version 2.2.0: For correctness and consistency the value used to indicate TDS 7.1 changed from
8.0 to 7.1 on pymssql 2.2.0.
Changed in version 2.1.3: 7.3 was added as a possible value.
MSSQLConnection.tds_version_tuple
New in version 2.2.0.
The TDS version used by this connection in tuple form which is more easily handled (parse, compare) pro-
grammatically. Can be one of (4, 2), (5, 0), (7, 0), (7, 1), (7, 2), (7, 3) or None if no TDS
version could be detected.
MSSQLConnection.cancel()
Cancel all pending results from the last SQL operation. It can be called more than one time in a row. No
exception is raised in this case.
MSSQLConnection.close()
Close the connection and free all memory used. It can be called more than one time in a row. No exception is
raised in this case.
MSSQLConnection.execute_query(query_string)
MSSQLConnection.execute_query(query_string, params)
This method sends a query to the MS SQL Server to which this object instance is connected. An exception
is raised on failure. If there are pending results or rows prior to executing this command, they are silently
discarded.
After calling this method you may iterate over the connection object to get rows returned by the query.
You can use Python formatting and all values get properly quoted. Please see examples for details.
This method is intented to be used on queries that return results, i.e. SELECT.
MSSQLConnection.execute_non_query(query_string)
MSSQLConnection.execute_non_query(query_string, params)
This method sends a query to the MS SQL Server to which this object instance is connected. After completion,
its results (if any) are discarded. An exception is raised on failure. If there are pending results or rows prior to
executing this command, they are silently discarded.
You can use Python formatting and all values get properly quoted. Please see examples for details.
This method is useful for INSERT, UPDATE, DELETE, and for Data Definition Language commands, i.e. when
you need to alter your database schema.
MSSQLConnection.execute_scalar(query_string)
MSSQLConnection.execute_scalar(query_string, params)
This method sends a query to the MS SQL Server to which this object instance is connected, then returns first
column of first row from result. An exception is raised on failure. If there are pending results or rows prior to
executing this command, they are silently discarded.
You can use Python formatting and all values get properly quoted. Please see examples for details.
This method is useful if you want just a single value from a query, as in the example below. This method works
in the same way as iter(conn).next()[0]. Remaining rows, if any, can still be iterated after calling this
method.
Example usage:
MSSQLConnection.execute_row(query_string)
MSSQLConnection.execute_row(query_string, params)
This method sends a query to the MS SQL Server to which this object instance is connected, then returns first
row of data from result. An exception is raised on failure. If there are pending results or rows prior to executing
this command, they are silently discarded.
You can use Python formatting and all values get properly quoted. Please see examples for details.
This method is useful if you want just a single row and don’t want or don’t need to iterate over the connection
object. This method works in the same way as iter(conn).next() to obtain single row. Remaining rows,
if any, can still be iterated after calling this method.
Example usage:
MSSQLConnection.get_header()
This method is infrastructure and doesn’t need to be called by your code. It gets the Python DB-API compliant
header information. Returns a list of 7-element tuples describing current result header. Only name and DB-API
compliant type is filled, rest of the data is None, as permitted by the specs.
MSSQLConnection.init_procedure(name)
Create an MSSQLStoredProcedure object that will be used to invoke thestored procedure with the given name.
MSSQLConnection.nextresult()
Move to the next result, skipping all pending rows. This method fetches and discards any rows remaining from
current operation, then it advances to next result (if any). Returns True value if next set is available, None
otherwise. An exception is raised on failure.
MSSQLConnection.select_db(dbname)
This function makes the given database the current one. An exception is raised on failure.
MSSQLConnection.__iter__()
MSSQLConnection.next()
New in version 2.1.0.
These methods implement the Python iterator protocol. You most likely will not call them directly, but indirectly
by using iterators.
MSSQLConnection.set_msghandler(handler)
New in version 2.1.1.
This method allows setting a message handler function for the connection to allow a client to gain access to the
messages returned from the server.
The signature of the message handler function handler passed to this method must be:
msgstate, severity and line will be integers, srvname, procname and msgtext will be strings.
MSSQLStoredProcedure.connection
An underlying MSSQLConnection object.
MSSQLStoredProcedure.name
The name of the procedure that this object represents.
MSSQLStoredProcedure.parameters
The parameters that have been bound to this procedure.
Exception hierarchy:
MSSQLException
|
+-- MSSQLDriverException
|
+-- MSSQLDatabaseException
exception _mssql.MSSQLDriverException
MSSQLDriverException is raised whenever there is a problem within _mssql – e.g. insufficient memory
for data structures, and so on.
exception _mssql.MSSQLDatabaseException
MSSQLDatabaseException is raised whenever there is a problem with the database – e.g. query
syntax error, invalid object name and so on. In this case you can use the following properties to access
details of the error:
number
The error code, as returned by SQL Server.
severity
The so-called severity level, as returned by SQL Server. If value of this property is less than the value of
_mssql.min_error_severity, such errors are ignored and exceptions are not raised.
state
The third error code, as returned by SQL Server.
message
The error message, as returned by SQL Server.
You can find an example of how to use this data at the bottom of _mssql examples page.
Because of the DB-API standard and because effort was made to make the interface of pymssql 2.x similar to that of
pymssql 1.x, there are only a few differences and usually upgrading is pretty easy.
There are a few differences though. . .
Note that we are talking about Python 2, because pymssql 1.x doesn’t work on Python 3.
pymssql 1.x will return str instances:
>>> pymssql.__version__
'1.0.3'
>>> conn.as_dict = True
>>> cursor = conn.cursor()
>>> cursor.execute("SELECT 'hello' AS str FROM foo")
>>> cursor.fetchall()
[{0: 'hello', 'str': 'hello'}]
>>> pymssql.__version__
u'2.0.1.2'
>>> conn.as_dict = True
>>> cursor = conn.cursor()
>>> cursor.execute("SELECT 'hello' AS str FROM foo")
>>> cursor.fetchall()
[{u'str': u'hello'}]
If your application has code that deals with str and unicode differently, then you may run into issues.
You can always convert a unicode to a str by encoding:
35
pymssql Documentation, Release 2.2.0.dev
In pymssql 2.x, uniqueidentifier columns are returned in results as instances of uuid.UUID and if you want
the bytes, like in pymssql 1.x, you have to use uuid.UUID.bytes_le to get them:
There are some other syntaxes for the host parameter that allow using a comma instead of a colon to delimit host
and port, to specify Windows hosts, to specify a specific SQL Server instance, etc.
In pymssql 2.x, the host parameter is supported (I am unsure if it has all of the functionality of pymssql 1.x). There
is also a parameter to specify the host that is called server. There is a separate parameter called port.
For parameter substitution, pymssql 2.x supports the format and pyformat PEP 249 paramstyles.
Note that for pyformat, PEP 249 only shows the example of a string substitution – e.g.:
%(name)s
It is not clear from PEP 249 whether other types should be supported, like:
%(name)d
%(name)f
However, in this mailing list thread, the general consensus is that the string format should be the only one required.
Note that pymssql 2.x does not support %(name)d, whereas pymssql 1.x did. So you may have to change code that
uses this notation:
>>> pymssql.__version__
u'2.0.1.2'
>>> pymssql.paramstyle
'pyformat'
to:
or:
If your Python program/script can’t connect to a SQL Server instance, try the following:
• By default SQL Server 2005 and newer don’t accept remote connections, you have to use SQL Server Sur-
face Area Configuration and/or SQL Server Configuration Manager to enable specific protocols and network
adapters; don’t forget to restart SQL Server after making these changes,
• If SQL Server is on a remote machine, check whether connections are not blocked by any intermediate firewall
device, firewall software, antivirus software, or other security facility,
• Check that you can connect with another tool.
If you are using FreeTDS, then you can use the included tsql command to try to connect – it looks
like this:
(1 row affected)
Note: Note that I use the -H option rather than the -S option to tsql. This is because with -H, it
will bypass reading settings from the freetds.conf file like port and tds version, and so
39
pymssql Documentation, Release 2.2.0.dev
If you can’t connect with tsql or other tools, then the problem is probably not pymssql; you prob-
ably have a problem with your server configuration (see below), FreeTDS Configuration, network,
etc.
If you can connect with tsql, then you should be able to connect with pymssql with something like
this:
If something like the above doesn’t work, then you can try to diagnose by setting one or both of the
following FreeTDS environment variables that control logging:
– TDSDUMP
– TDSDUMPCONFIG
Either or both of these can be set. They can be set to a filename or to stdout or stderr.
These will cause FreeTDS to output a ton of information about what it’s doing and you may very
well spot that it’s not using the port that you expected or something similar. For example:
>>> import os
>>> os.environ['TDSDUMP'] = 'stdout'
>>>
>>> import pymssql
>>> conn = pymssql.connect(server="sqlserverhost")
log.c:194:Starting log file for FreeTDS 0.92.dev.20140102
on 2014-01-09 14:05:32 with debug flags 0x4fff.
config.c:731:Setting 'dump_file' to 'stdout' from $TDSDUMP.
...
dblib.c:7934:20013: "Unknown host machine name"
dblib.c:7955:"Unknown host machine name", client returns 2 (INT_CANCEL)
util.c:347:tdserror: client library returned TDS_INT_CANCEL(2)
util.c:370:tdserror: returning TDS_INT_CANCEL(2)
login.c:418:IP address pointer is empty
login.c:420:Server sqlserverhost:1433 not found!
...
Note: Note that pymssql will use a default port of 1433, despite any ports you may have specified in
your freetds.conf file. So if you have SQL Server running on a port other than 1433, you must
explicitly specify the port in your call to pymssql.connect. You cannot rely on it to pick up
the port in your freetds.conf, even though tsql -S might do this. This is why I recommend
using tsql -H instead for diagnosing connection problems.
It is also useful to know that tsql -C will output a lot of information about FreeTDS, that can be
useful for diagnosing problems:
$ tsql -C
Compile-time settings (established with the "configure" script)
Version: freetds v0.92.dev.20140102
freetds.conf directory: /usr/local/etc
MS db-lib source compatibility: no
Sybase binary compatibility: no
Thread safety: yes
iconv library: yes
TDS version: 5.0
iODBC: yes
unixodbc: no
SSPI "trusted" logins: no
Kerberos: no
OpenSSL: no
GnuTLS: no
• If you use pymssql on Linux/Unix with FreeTDS, check that FreeTDS’s configuration is ok and that it can be
found by pymssql. The easiest way is to test connection using tsql utility which can be found in FreeTDS
package. See FreeTDS Configuration for more info,
If you use pymssql on Linux/*nix and you suspect that returned dates are not correct, please read the FreeTDS and
dates page.
There is a known issue where some versions of pymssql 1.x (pymssql 1.0.2 is where I’ve seen this) work well with
FreeTDS 0.82, but return no rows when used with newer versions of FreeTDS, such as FreeTDS 0.91. At SurveyMon-
key, we ran into this problem when we were using pymssql 1.0.2 and then upgraded servers from Ubuntu 10 (which
includes FreeTDS 0.82) to Ubuntu 12 (which includes FreeTDS 0.91).
E.g.:
>>> import pymssql
>>> pymssql.__version__
'1.0.2'
>>> conn = pymssql.connect(host='127.0.0.1:1433', user=user,
... password=password, database='tempdb')
>>> cursor = conn.cursor()
>>> cursor.execute('SELECT 1')
>>> cursor.fetchall()
[]
See GitHub issue 137: pymssql 1.0.2: No result rows are returned from queries with newer versions of FreeTDS.
There are two way to fix this problem:
1. (Preferred) Upgrade to pymssql 2.x. pymssql 1.x is not actively being worked on. pymssql 2.x is rewritten in
Cython, is actively maintained, and offers better performance, Python 3 support, etc. E.g.:
2. Upgrade to pymssql 1.0.3. This is identical to pymssql 1.0.2 except that it has a very small change that makes it
so that it works with newer versions of FreeTDS as well as older versions.
E.g.:
One possible cause of your result rows missing columns is if you are using a connection or cursor with
as_dict=True and your query has columns without names – for example:
>>> cursor.execute("SELECT MAX(x) AS [MAX(x)] FROM (VALUES (1), (2), (3)) AS foo(x)")
>>> cursor.fetchall()
[{u'MAX(x)': 3}]
This behavior was changed in https://github.com/pymssql/pymssql/pull/160 – with this change, if you specify
as_dict=True and omit column names, an exception will be raised:
You may notice that pymssql will unserialize a DATETIME column to a datetime.datetime instance, but it will
unserialize DATE and TIME columns as simple strings. For example:
>>> cursor.execute("""
... CREATE TABLE dates_and_times (
... datetime DATETIME,
... date DATE,
... time TIME,
... )
... """)
>>> cursor.execute("INSERT INTO dates_and_times VALUES (GETDATE(), '20140109', '6:17')
˓→")
Yep, so the problem here is that DATETIME has been supported by FreeTDS for a long time, but DATE and TIME are
newer types in SQL Server, Microsoft never added support for them to db-lib and FreeTDS added support for them in
version 0.95.
If you need support for these data types (i.e. they get returned from the database as their native corresponding Python
data types instead of as strings) as well as for the DATETIME2 one, then make sure the following conditions are met:
• You are connecting to SQL Server 2008 or newer.
• You are using FreeTDS 0.95 or newer.
• You are using TDS protocol version 7.3 or newer.
It may mean that the FreeTDS library is unavailable, or that the dynamic linker is unable to find it. Check that it is
installed and that the path to libsybdb.so is in /etc/ld.so.conf file. Then do ldconfig as root to refresh
9.5. pymssql does not unserialize DATE and TIME columns to datetime.date and 43
datetime.time instances
pymssql Documentation, Release 2.2.0.dev
linker database. On Solaris, I just set the LD_LIBRARY_PATH environment variable to the directory with the library
just before launching Python.
pymssql 2.x bundles the FreeTDS sybdb library for supported platforms. This error may show up in 2.x versions if
you are trying to build with your own FreeTDS.
9.7 “DB-Lib error message 20004, severity 9: Read from SQL server
failed” error appears
If the above hasn’t covered the problem you can send a message describing it to the pymssql mailing list. You can also
consult FreeTDS troubleshooting page for issues related to the TDS protocol.
10.1 Building
Note: If you need to connect to Azure make sure FreeTDS is built with SSL support. Instructions on how to do this
are out of the scope of this document.
10.1.1 Windows
MinGW
45
pymssql Documentation, Release 2.2.0.dev
MS Visual C++
Environment Setup:
The commands below should be ran inside a Visual Studio command prompt or a command prompt window where
the vcsvars*.bat file has been previously run so it can set the needed environment vars.
Building FreeTDS:
Fixing build errors: I ran into a couple build errors when using VS 2008, see the following links for resolutions:
• http://www.freetds.org/userguide/osissues.htm
• http://lists.ibiblio.org/pipermail/freetds/2010q4/026343.html
When this is done, the following files should be available (depending on CONFIGURATION and PLATFORM used
above):
src\dblib\<PLATFORM>\<CONFIGURATION>\db-lib.lib
src\tds\<PLATFORM>\<CONFIGURATION>\tds.lib
for example:
src\dblib\win32\release\db-lib.lib
src\tds\win32\release\tds.lib
<pymssql root>\freetds\vs2008_<bitness>\lib\
for example:
<pymssql root>\freetds\vs2008_32\lib\
<pymssql root>\freetds\vs2008_64\lib\
The location obviously depends on whether you are performing a 32 or 64 bit build.
Note: This process is currently only tested with Visual Studio 2008 targeting a 32-bit build. If you run into problems,
please post to the mailing list.
10.1.2 Unix
10.2 Testing
You need to setup a tests.cfg file in tests/ with the correct DB connection information for your environment:
cp tests/tests.cfg.tpl tests/tests.cfg
vim|emacs|notepad tests/tests.cfg
cd tests # optional
py.test
Which will go through and run all the tests with the settings from the DEFAULT section of tests.cfg.
To run with a different tests.cfg section:
py.test --pymssql-section=<secname>
example:
py.test --pymssql-section=AllTestsWillRun
10.2. Testing 47
pymssql Documentation, Release 2.2.0.dev
py.test tests/test_types.py
py.test tests/test_types.py tests/test_sprocs.py
py.test tests/test_types.py::TestTypes
py.test tests/test_types.py::TestTypes::test_image
11.1 Summary
Make sure that FreeTDS is compiled with --enable-msdblib configure option, or your queries will return
wrong dates – "2010-00-01" instead of "2010-01-01".
11.2 Details
There’s an obscure problem on Linux/*nix that results in dates shifted back by 1 month. This behaviour is caused by
different dbdatecrack() prototypes in Sybase Open Client DB-Library/C and the Microsoft SQL DB Library for
C. The first one returns month as 0..11 whereas the second gives month as 1..12. See this FreeTDS mailing list post,
Microsoft manual for dbdatecrack(), and Sybase manual for dbdatecrack() for details.
FreeTDS, which is used on Linux/*nix to connect to Sybase and MS SQL servers, tries to imitate both modes:
• Default behaviour, when compiled without --enable-msdblib, gives dbdatecrack() which is Sybase-
compatible,
• When configured with --enable-msdblib, the dbdatecrack() function is compatible with MS SQL
specs.
pymssql requires MS SQL mode, evidently. Unfortunately at runtime we can’t reliably detect which mode FreeTDS
was compiled in (as of FreeTDS 0.63). Thus at runtime it may turn out that dates are not correct. If there was a way
to detect the setting, pymssql would be able to correct dates on the fly.
If you can do nothing about FreeTDS, there’s a workaround. You can redesign your queries to return string instead of
bare date:
49
pymssql Documentation, Release 2.2.0.dev
This way SQL will send you string representing the date instead of binary date in datetime or smalldatetime format,
which has to be processed by FreeTDS and pymssql.
Starting with version 2.1.1 pymssql can be used to connect to Microsoft Azure SQL Database.
Make sure the following requirements are met:
• Use FreeTDS 0.91 or newer
• Use TDS protocol 7.1 or newer
• Make sure FreeTDS is built with SSL support
• Specify the database name you are connecting to in the database parameter of the relevant connect() call
• IMPORTANT: Do not use username@server.database.windows.net for the user parameter of the
relevant connect() call! You must use the shorter username@server form instead!
Example:
[myalias]
host = xxx.database.windows.net
tds version = 7.1
...
51
pymssql Documentation, Release 2.2.0.dev
Docker
(Experimental)
There is a pymssql Docker image on the Docker Registry at:
https://registry.hub.docker.com/u/pymssql/pymssql/
The image bundles:
• Ubuntu 14.04 LTS (trusty)
• Python 2.7.6
• pymssql 2.1.2.dev
• FreeTDS 0.91
• SQLAlchemy 0.9.8
• Alembic 0.7.4
• Pandas 0.15.2
• Numpy 1.9.1
• IPython 2.3.1
To try it, first download the image (this requires Internet access and could take a while):
By default, if no command is specified, an IPython shell is invoked. You can override the command if you wish – e.g.:
53
pymssql Documentation, Release 2.2.0.dev
See the Docker docs for installation instructions for a number of platforms; you can try this link: https://docs.docker.
com/installation/#installation
Change log
Change Log
==========
General
-------
- Stop using 7.1 as default value for the TDS protocol version used in connections.
Now you need to specify a TDS protocol version explicitly by using any of
the supported mechanisms (in descending order of precedence):
Features
--------
- Support for new in SQL Server 2008 ``DATE``, ``TIME`` and ``DATETIME2`` data
types (GH-156). The following conditions need to be additionally met so
values of these column types can be returned from the database as their
native corresponding Python data types instead of as strings:
55
pymssql Documentation, Release 2.2.0.dev
Bug fixes
---------
Features
--------
Bug fixes
---------
- Add support for reporting TDS version 7.3 is in use via the ``tds_version``
property of a ``_mssql``-level connection.
.. attention:: Windows users: You need to download and install additional DLLs
We are trying to find a balance between security and convenience and will
be evaluating the situation for future releases. Your feedback is greatly
welcome.
General
-------
- Add ability to set TDS protocol version from pymssql when connecting to SQL
Server. For the remaining pymssql 2.1.x releases its default value will be 7.1
(GH-323)
- Add Dockerfile and a Docker image and instructions on how to use it (GH-258).
This could be a convenient way to use pymssql without having to build stuff.
See http://pymssql.readthedocs.org/en/latest/intro.html#docker
Thanks Marc Abramowitz.
- Send pymssql version in the appname TDS protocol login record field when the
application doesn't provide one (GH-354)
Bug fixes
---------
- Fix build fatal error when using Cython >= 0.22 (GH-311)
Documentation
-------------
Internals
---------
57
pymssql Documentation, Release 2.2.0.dev
- Make it possible to build official release files (sdist, wheels) on Travis &
AppVeyor.
Features
--------
``_mssql`` now allows you to install your own *message handlers* written in
Python. See the ``_msssql`` examples and reference sections of the
documentation for more details.
.. note:: If you need to connect to Azure make sure you use FreeTDS 0.91 or
newer.
It is now possible to customize the SQL statements sent right after the
connection is established (e.g. ``'SET ANSI_NULLS ON;'``). Previously
it was a hard-coded list of queries. See the ``_mssql.MSSQLConnection``
documentation for more details.
Bug fixes
---------
- Handle errors when calling Stored Procedures via the ``.callproc()`` pymssql
cursor method. Now it will raise a DB-API ``DatabaseException``; previously
it allowed a ``_mssql.MSSQLDatabaseException`` exception to surface.
The value returned for TDS version 7.1 is still 8.0 for backward
compatibility (this is because such feature got added in times when
Microsoft documentation labeled the two protocol versions that followed 7.0
as 8.0 and 9.0; later it changed them to 7.1 and 7.2 respectively) and will
be corrected in a future release (2.2).
- Check lower bound value when convering integer values from to Python to SQL
(GH-238)
Internals
---------
- Tests: Modified a couple of test cases so the full suite can be run against
SQL Server 2005.
Features
--------
(continues on next page)
59
pymssql Documentation, Release 2.2.0.dev
See:
* https://github.com/pymssql/pymssql/pull/149
* https://github.com/pymssql/pymssql/pull/162
* https://github.com/pymssql/pymssql/pull/164
* https://github.com/pymssql/pymssql/pull/165
* https://github.com/pymssql/pymssql/pull/166
* https://github.com/pymssql/pymssql/pull/167
* https://github.com/pymssql/pymssql/pull/169
* https://github.com/pymssql/pymssql/pull/174
* https://github.com/pymssql/pymssql/pull/175
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.
See https://github.com/pymssql/pymssql/pull/135
See:
* https://github.com/pymssql/pymssql/pull/151
See:
* https://github.com/pymssql/pymssql/pull/160
* https://github.com/pymssql/pymssql/pull/168
- Performance improvements
You are most likely to notice a difference from these when you are
fetching a large number of rows.
See:
* https://github.com/pymssql/pymssql/pull/158
* https://github.com/pymssql/pymssql/pull/159
This drops the previous method of building up a row tuple and switches
to using the CPython API, which allows you to create a correctly sized
tuple at the beginning and simply fill it in. This appears to offer
around a 10% boost when fetching rows from a table where the data is
already in memory.
Thanks Damien, Churchill!
See:
* https://github.com/pymssql/pymssql/pull/178
* https://github.com/pymssql/pymssql/pull/171
61
pymssql Documentation, Release 2.2.0.dev
Use the bytesarray type added in Python 2.6 to signify that this is
binary data and to quote it accordingly. Also modify the handling of
str/bytes types checking the first 2 characters for b'0x' and insert
that as binary data.
See:
* https://github.com/pymssql/pymssql/pull/179
See:
* https://github.com/pymssql/pymssql/pull/143
* https://github.com/pymssql/pymssql/commit/1689c83878304f735eb38b1c63c31e210b028ea7
* See https://github.com/pymssql/pymssql/commit/
˓→ fd317df65fa62691c2af377e4661defb721b2699
* See: https://github.com/pymssql/pymssql/pull/183
Bug Fixes
---------
* See: https://github.com/pymssql/pymssql/issues/142
See:
* https://github.com/pymssql/pymssql/issues/145
* https://github.com/pymssql/pymssql/pull/146
* https://github.com/pymssql/pymssql/pull/151
See: https://github.com/pymssql/pymssql/issues/177
* See: https://github.com/pymssql/pymssql/pull/181
* See: https://github.com/pymssql/pymssql/pull/182
* Better performance
* Thread safety
* Fuller test suite
* Support for Python 3
* Continuous integration via `Travis CI`_
* Easier to understand code, due to `Cython`_
.. _PyPI: https://pypi.python.org/pypi/pymssql/2.0.0
.. _Travis CI: https://travis-ci.org/pymssql/pymssql
.. _Cython: http://cython.org/
.. _ChangeLog: https://github.com/pymssql/pymssql/blob/master/ChangeLog
63
pymssql Documentation, Release 2.2.0.dev
65
pymssql Documentation, Release 2.2.0.dev
67
pymssql Documentation, Release 2.2.0.dev
69
pymssql Documentation, Release 2.2.0.dev
* Added ChangeLog
* API Change: add 6th parameter 'port' to connect
* Don't close connection on cursor close (noted by Alberto Pastore on the
˓→sourceforge project page)
71
pymssql Documentation, Release 2.2.0.dev
TODO
15.1 Documentation
73
pymssql Documentation, Release 2.2.0.dev
_
_mssql, 27
p
pymssql, 19
75
pymssql Documentation, Release 2.2.0.dev
Symbols E
__full_version__ (in module _mssql), 27 Error, 24
__full_version__ (in module pymssql), 19 execute() (_mssql.MSSQLStoredProcedure method), 32
__iter__() (_mssql.MSSQLConnection method), 31 execute() (pymssql.Cursor method), 23
__iter__() (pymssql.Cursor method), 24 execute_non_query() (_mssql.MSSQLConnection
__version__ (in module _mssql), 27 method), 30
__version__ (in module pymssql), 19 execute_query() (_mssql.MSSQLConnection method),
_mssql (module), 27 30
execute_row() (_mssql.MSSQLConnection method), 31
A execute_scalar() (_mssql.MSSQLConnection method),
apilevel (in module pymssql), 19 30
autocommit() (pymssql.Connection method), 22 executemany() (pymssql.Cursor method), 24
B F
bind() (_mssql.MSSQLStoredProcedure method), 32 fetchall() (pymssql.Cursor method), 24
fetchmany() (pymssql.Cursor method), 24
C fetchone() (pymssql.Cursor method), 24
cancel() (_mssql.MSSQLConnection method), 30
charset (_mssql.MSSQLConnection attribute), 29
G
close() (_mssql.MSSQLConnection method), 30 get_dbversion() (in module pymssql), 21
close() (pymssql.Connection method), 22 get_header() (_mssql.MSSQLConnection method), 31
close() (pymssql.Cursor method), 23 get_max_connections() (in module _mssql), 27
ColumnsWithoutNamesError, 25 get_max_connections() (in module pymssql), 21
commit() (pymssql.Connection method), 23
connect() (in module pymssql), 20 I
connected (_mssql.MSSQLConnection attribute), 29 identity (_mssql.MSSQLConnection attribute), 29
connection (_mssql.MSSQLStoredProcedure attribute), init_procedure() (_mssql.MSSQLConnection method),
32 31
Connection (class in pymssql), 22 IntegrityError, 25
connection (pymssql.Cursor attribute), 23 InterfaceError, 24
Cursor (class in pymssql), 23 InternalError, 25
cursor() (pymssql.Connection method), 22
L
D lastrowid (pymssql.Cursor attribute), 23
DatabaseError, 24 login_timeout (in module _mssql), 27
DataError, 24
debug_queries (_mssql.MSSQLConnection attribute), 29 M
message (_mssql.MSSQLDatabaseException attribute),
33
77
pymssql Documentation, Release 2.2.0.dev
N V
name (_mssql.MSSQLStoredProcedure attribute), 32 VERSION (in module _mssql), 27
next() (_mssql.MSSQLConnection method), 31 VERSION (in module pymssql), 19
next() (pymssql.Cursor method), 24
nextresult() (_mssql.MSSQLConnection method), 31 W
nextset() (pymssql.Cursor method), 24
Warning, 24
NotSupportedError, 25
number (_mssql.MSSQLDatabaseException attribute),
33
O
OperationalError, 25
P
parameters (_mssql.MSSQLStoredProcedure attribute),
32
paramstyle (in module pymssql), 19
ProgrammingError, 25
pymssql (module), 19
Python Enhancement Proposals
PEP 249#operationalerror, 24
PEP 440, 19
PEP 513, 1
Q
query_timeout (_mssql.MSSQLConnection attribute), 29
R
rollback() (pymssql.Connection method), 23
rowcount (pymssql.Cursor attribute), 23
rownumber (pymssql.Cursor attribute), 23
rows_affected (_mssql.MSSQLConnection attribute), 29
S
select_db() (_mssql.MSSQLConnection method), 31
set_max_connections() (in module _mssql), 27
set_max_connections() (in module pymssql), 21
set_msghandler() (_mssql.MSSQLConnection method),
31
set_wait_callback() (in module pymssql), 21
setinputsizes() (pymssql.Cursor method), 24
setoutputsize() (pymssql.Cursor method), 24
severity (_mssql.MSSQLDatabaseException attribute),
33
StandardError, 24
state (_mssql.MSSQLDatabaseException attribute), 33
78 Index