pytds – main module¶
DB-SIG compliant module for communicating with MS SQL servers
-
class
pytds.
Connection
[source]¶ Connection object, this object should be created by calling
connect()
-
as_dict
¶ Instructs all cursors this connection creates to return results as a dictionary rather than a tuple.
-
autocommit
¶ The current state of autocommit on the connection.
-
autocommit_state
¶ An alias for autocommit, provided for compatibility with pymssql
-
chunk_handler
¶ Returns current chunk handler Default is MemoryChunkedHandler()
-
close
()[source]¶ Close connection to an MS SQL Server.
This function tries to close the connection and free all memory used. It can be called more than once in a row. No exception is raised in this case.
-
cursor
()[source]¶ Return cursor object that can be used to make queries and fetch results from the database.
-
isolation_level
¶ Isolation level for transactions, for possible values see Isolation level constants
See also
SET TRANSACTION ISOLATION LEVEL in MSSQL documentation
-
mars_enabled
¶ Whether MARS is enabled or not on connection
-
product_version
¶ Version of the MSSQL server
-
tds_version
¶ Version of tds protocol that is being used by this connection
-
-
class
pytds.
Cursor
(conn, session, tzinfo_factory)[source]¶ This class represents a database cursor, which is used to issue queries and fetch results from a database connection.
-
callproc
(procname, parameters=())[source]¶ Call a stored procedure with the given name.
Parameters: - procname (str) – The name of the procedure to call
- parameters (sequence) – The optional parameters for the procedure
-
connection
¶ Provides link back to
Connection
of this cursor
-
copy_to
(file, table_or_view, sep='\t', columns=None, check_constraints=False, fire_triggers=False, keep_nulls=False, kb_per_batch=None, rows_per_batch=None, order=None, tablock=False, schema=None, null_string=None)[source]¶ Experimental. Efficiently load data to database from file using
BULK INSERT
operationParameters: - file – Source file-like object, should be in csv format
- table_or_view (str) – Destination table or view in the database
Optional parameters:
Parameters: - sep (str) – Separator used in csv file
- columns (list) – List of column names in target table to insert to, if not provided will insert into all columns
- check_constraints (bool) – Check table constraints for incoming data
- fire_triggers (bool) – Enable or disable triggers for table
- keep_nulls (bool) – If enabled null values inserted as-is, instead of inserting default value for column
- kb_per_batch (int) – Kilobytes per batch can be used to optimize performance, see MSSQL server documentation for details
- rows_per_batch (int) – Rows per batch can be used to optimize performance, see MSSQL server documentation for details
- order (list) – The ordering of the data in source table. List of columns with ASC or DESC suffix.
E.g.
['order_id ASC', 'name DESC']
Can be used to optimize performance, see MSSQL server documentation for details - tablock – Enable or disable table lock for the duration of bulk load
- schema – Name of schema for table or view, if not specified default schema will be used
- null_string – String that should be interpreted as a NULL when reading the CSV file.
-
description
¶ Cursor description, see http://legacy.python.org/dev/peps/pep-0249/#description
-
execute_scalar
(query_string, params=None)[source]¶ 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.
This method accepts Python formatting. Please see execute_query() for details.
This method is useful if you want just a single value, as in:
conn.execute_scalar('SELECT COUNT(*) FROM employees')
This method works in the same way as
iter(conn).next()[0]
. Remaining rows, if any, can still be iterated after calling this method.
-
fetchmany
(size=None)[source]¶ Fetches next multiple rows
Parameters: size – Maximum number of rows to return, default value is cursor.arraysize Returns: List of rows
-
messages
¶ Messages generated by server, see http://legacy.python.org/dev/peps/pep-0249/#cursor-messages
-
native_description
¶ todo document
-
nextset
()[source]¶ Move to next recordset in batch statement, all rows of current recordset are discarded if present.
Returns: true if successful or None
when there are no more recordsets
-
return_value
¶ Alias to
get_proc_return_status()
-
rowcount
¶ Number of rows affected by previous statement
Returns: -1 if this information was not supplied by MSSQL server
-
static
setoutputsize
(column=0)[source]¶ This method does nothing, as permitted by DB-API specification.
-
spid
¶ MSSQL Server’s SPID (session id)
-
-
pytds.
apilevel
= '2.0'¶ Compliant with DB SIG 2.0
-
pytds.
connect
(dsn=None, database=None, user=None, password=None, timeout=None, login_timeout=15, as_dict=None, appname=None, port=None, tds_version=1946157060, autocommit=False, blocksize=4096, use_mars=False, auth=None, readonly=False, load_balancer=None, use_tz=None, bytes_to_unicode=True, row_strategy=None, failover_partner=None, server=None, cafile=None, validate_host=True, enc_login_only=False)[source]¶ Opens connection to the database
Parameters: - dsn (string) – SQL server host and instance: <host>[<instance>]
- failover_partner (string) – secondary database host, used if primary is not accessible
- database (string) – the database to initially connect to
- user (string) – database user to connect as
- password (string) – user’s password
- timeout (int) – query timeout in seconds, default 0 (no timeout)
- login_timeout (int) – timeout for connection and login in seconds, default 15
- as_dict (boolean) – whether rows should be returned as dictionaries instead of tuples.
- appname (string) – Set the application name to use for the connection
- port (int) – the TCP port to use to connect to the server
- tds_version (int) – Maximum TDS version to use, should only be used for testing
- autocommit (bool) – Enable or disable database level autocommit
- blocksize (int) – Size of block for the TDS protocol, usually should not be used
- use_mars (bool) – Enable or disable MARS
- auth – An instance of authentication method class, e.g. Ntlm or Sspi
- readonly (bool) – Allows to enable read-only mode for connection, only supported by MSSQL 2012, earlier versions will ignore this parameter
- load_balancer – An instance of load balancer class to use, if not provided will not use load balancer
- use_tz – Provides timezone for naive database times, if not provided date and time will be returned in naive format
- bytes_to_unicode (bool) – If true single byte database strings will be converted to unicode Python strings,
otherwise will return strings as
bytes
without conversion. - row_strategy (function of list of column names returning row factory) – strategy used to create rows, determines type of returned rows, can be custom or one of:
tuple_row_strategy()
,list_row_strategy()
,dict_row_strategy()
,namedtuple_row_strategy()
,recordtype_row_strategy()
- cafile (str) – Name of the file containing trusted CAs in PEM format, if provided will enable TLS
- validate_host (bool) – Host name validation during TLS connection is enabled by default, if you disable it you will be vulnerable to MitM type of attack.
- enc_login_only (bool) – Allows you to scope TLS encryption only to an authentication portion. This means that anyone who can observe traffic on your network will be able to see all your SQL requests and potentially modify them.
Returns: An instance of
Connection
-
pytds.
namedtuple_row_strategy
(column_names)[source]¶ Namedtuple row strategy, rows returned as named tuples
Column names that are not valid Python identifiers will be replaced with col<number>_
-
pytds.
paramstyle
= 'pyformat'¶ This module uses extended python format codes
-
pytds.
recordtype_row_strategy
(column_names)[source]¶ Recordtype row strategy, rows returned as recordtypes
Column names that are not valid Python identifiers will be replaced with col<number>_
-
pytds.
threadsafety
= 1¶ Module may be shared, but not connections
pytds.login – login with NTLM and SSPI¶
-
class
pytds.login.
NtlmAuth
(user_name, password)[source]¶ NTLM authentication, uses Python implementation
Parameters: - user_name (str) – User name
- password (str) – User password
-
class
pytds.login.
SspiAuth
(user_name='', password='', server_name='', port=None, spn=None)[source]¶ SSPI authentication
Platform: Windows Required parameters are server_name and port or spn
Parameters: - user_name (str) – User name, if not provided current security context will be used
- password (str) – User password, if not provided current security context will be used
- server_name (str) – MSSQL server host name
- port (int) – MSSQL server port
- spn (str) – Service name