pytds – main module¶
DB-SIG compliant module for communicating with MS SQL servers
- pytds.apilevel = '2.0'¶
Compliant with DB SIG 2.0
- pytds.connect(dsn: str | None = None, database: str | None = None, user: str | None = None, password: str | None = None, timeout: float | None = None, login_timeout: float = 15, as_dict: bool | None = None, appname: str | None = None, port: int | None = None, tds_version: int = 1946157060, autocommit: bool = False, blocksize: int = 4096, use_mars: bool = False, auth: AuthProtocol | None = None, readonly: bool = False, load_balancer: LoadBalancer | None = None, use_tz: tzinfo | None = None, bytes_to_unicode: bool = True, row_strategy: Callable[[Iterable[str]], Callable[[Iterable[Any]], Any]] | None = None, failover_partner: str | None = None, server: str | None = None, cafile: str | None = None, sock: socket | None = None, validate_host: bool = True, enc_login_only: bool = False, disable_connect_retry: bool = False, pooling: bool = False, use_sso: bool = False, isolation_level: int = 0)[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.
use_sso – Enables SSO login, e.g. Kerberos using SSPI on Windows and kerberos package on other platforms. Cannot be used together with auth parameter.
- Returns:
An instance of
Connection
- pytds.paramstyle = 'pyformat'¶
This module uses extended python format codes
- pytds.threadsafety = 1¶
Module may be shared, but not connections
pytds.login – various login mechanisms, e.g. NTLM, Negotiate, SSPI¶
- class pytds.login.NtlmAuth(user_name: str, password: str, ntlm_compatibility: int = 3)[source]¶
This class is deprecated since ntlm-auth package, on which it depends, is deprecated. Instead use
SpnegoAuth
.NTLM authentication, uses Python implementation (ntlm-auth)
For more information about NTLM authentication see https://github.com/jborean93/ntlm-auth
- Parameters:
user_name (str) – User name
password (str) – User password
ntlm_compatibility (int) – NTLM compatibility level, default is 3(NTLMv2)
- class pytds.login.SpnegoAuth(*args, **kwargs)[source]¶
Authentication using Negotiate protocol, uses implementation provided pyspnego package
Takes same parameters as spnego.client function.
- class pytds.login.SspiAuth(user_name: str = '', password: str = '', server_name: str = '', port: int | None = None, spn: str | None = 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
pytds.tds_base – Internal classes¶
- exception pytds.tds_base.ClosedConnectionError[source]¶
This error is raised when MSSQL server closes connection.
- class pytds.tds_base.Column(name='', type=None, flags=1, value=None)[source]¶
Describes table column. Can be used to define schema for bulk insert.
Following flags can be used for columns in flags parameter:
fNullable
- column can contain NULL valuesfCaseSen
- column is case-sensitivefReadWrite
- TODO documentfIdentity
- TODO documentfComputed
- TODO document
- Parameters:
name (str) – Name of the column
type – Type of a column, e.g.
pytds.tds_types.IntType
flags – Combination of flags for the column, multiple flags can be combined using binary or operator. Possible flags are described above.
- exception pytds.tds_base.DataError[source]¶
This error is raised when input parameter contains data which cannot be converted to acceptable data type.
- exception pytds.tds_base.DatabaseError(msg: str, exc: Any | None = None)[source]¶
This error is raised when MSSQL server returns an error which includes error number
- exception pytds.tds_base.IntegrityError(msg: str, exc: Any | None = None)[source]¶
TODO add documentation
- exception pytds.tds_base.InternalError(msg: str, exc: Any | None = None)[source]¶
TODO add documentation
- exception pytds.tds_base.LoginError(msg: str, exc: Any | None = None)[source]¶
This error is raised if provided login credentials are invalid
- exception pytds.tds_base.NotSupportedError(msg: str, exc: Any | None = None)[source]¶
TODO add documentation
- exception pytds.tds_base.OperationalError(msg: str, exc: Any | None = None)[source]¶
TODO add documentation
- class pytds.tds_base.Param(name: str = '', type=None, value=None, flags: int = 0)[source]¶
Describes typed parameter. Can be used to explicitly specify type of the parameter in the parametrized query.
- Parameters:
name (str) – Optional name of the parameter
type – Type of the parameter, e.g.
pytds.tds_types.IntType
- class pytds.tds_base.PreLoginToken[source]¶
PRELOGIN token option identifiers, corresponds to PL_OPTION_TOKEN in the spec.
- exception pytds.tds_base.ProgrammingError(msg: str, exc: Any | None = None)[source]¶
TODO add documentation
- class pytds.tds_base.TransportProtocol(*args, **kwargs)[source]¶
This protocol mimics socket protocol
- pytds.tds_base.force_unicode(s)[source]¶
Convert input into a string. If input is a byte array, it will be decoded using UTF8 decoder.
- pytds.tds_base.iterdecode(iterable, codec)[source]¶
Uses an incremental decoder to decode each chunk of string in iterable. This function is a generator.
- Parameters:
iterable – Iterable object which yields raw data to be decoded.
codec – An instance of a codec which will be used for decoding.
- pytds.tds_base.read_chunks(stm, size)[source]¶
Reads exactly size bytes from stm and produces chunks
May call stm.read multiple times until required number of bytes is read. If EOF is reached before size bytes are read will raise
ClosedConnectionError
- Parameters:
stm – Stream to read bytes from, should have read method, this read method can return less than requested number of bytes.
size – Number of bytes to read.
- pytds.tds_base.readall(stm, size)[source]¶
Reads exactly size bytes from stm
May call stm.read multiple times until required number of bytes read. If EOF is reached before size bytes are read will raise
ClosedConnectionError
- Parameters:
stm – Stream to read bytes from, should have read method this read method can return less than requested number of bytes.
size – Number of bytes to read.
- Returns:
Bytes buffer of exactly given size.
- pytds.tds_base.readall_fast(stm, size)[source]¶
Slightly faster version of readall, it reads no more than two chunks. Meaning that it can only be used to read small data that doesn’t span more that two packets.
- Parameters:
stm – Stream to read from, should have read method.
size – Number of bytes to read.
- Returns:
- pytds.tds_base.skipall(stm, size)[source]¶
Skips exactly size bytes in stm
If EOF is reached before size bytes are skipped will raise
ClosedConnectionError
- Parameters:
stm – Stream to skip bytes in, should have read method this read method can return less than requested number of bytes.
size – Number of bytes to skip.
- pytds.tds_base.tds7_crypt_pass(password: str) bytearray [source]¶
Mangle password according to tds rules
- Parameters:
password – Password str
- Returns:
Byte-string with encoded password
pytds.tds_types – Column type classes¶
This module implements various data types supported by Microsoft SQL Server
- class pytds.tds_types.BaseDateTime73Serializer(precision=None, scale=None, size=None)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.BaseDateTimeSerializer(precision=None, scale=None, size=None)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.BasePrimitiveTypeSerializer(precision=None, scale=None, size=None)[source]¶
Base type for primitive TDS data types.
Primitive type is a fixed size type with no type arguments. All primitive TDS types should derive from it. In addition actual types should provide the following:
type - class variable storing type identifier
declaration - class variable storing name of sql type
isntance - class variable storing instance of class
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.BaseTypeSerializer(precision=None, scale=None, size=None)[source]¶
Base type for TDS data types.
All TDS types should derive from it. In addition actual types should provide the following:
type - class variable storing type identifier
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.BaseTypeSerializerN(size)[source]¶
Base type for nullable TDS data types.
All nullable TDS types should derive from it. In addition actual types should provide the following:
type - class variable storing type identifier
subtypes - class variable storing dict {subtype_size: subtype_instance}
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.BigIntSerializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.BitSerializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.DateTime2Serializer(typ)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.DateTimeOffsetSerializer(typ)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.DateTimeSerializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.FloatSerializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.Image70Serializer(size=0, table_name='')[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.IntSerializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.Money4Serializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.Money8Serializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.MsDateSerializer(typ)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- class pytds.tds_types.MsDecimalSerializer(precision=18, scale=0)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.MsTimeSerializer(typ)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.MsUniqueSerializer(precision=None, scale=None, size=None)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.NText70Serializer(size=0, table_name='', collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0))[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.NText71Serializer(size=0, table_name='', collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0))[source]¶
- class pytds.tds_types.NText72Serializer(size=0, table_name_parts=(), collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0))[source]¶
- class pytds.tds_types.NVarChar70Serializer(size, collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0))[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.NVarChar71Serializer(size, collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0))[source]¶
- class pytds.tds_types.NVarChar72Serializer(size, collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0))[source]¶
- class pytds.tds_types.NVarCharMaxSerializer(collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0))[source]¶
-
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.RealSerializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.SmallDateTimeSerializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.SmallIntSerializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.TableSerializer(table_type, columns_serializers)[source]¶
Used to serialize table valued parameters
spec: https://msdn.microsoft.com/en-us/library/dd304813.aspx
- write(w, val)[source]¶
Writes remaining part of TVP_TYPE_INFO structure, resuming from TVP_COLMETADATA
specs: https://msdn.microsoft.com/en-us/library/dd302994.aspx https://msdn.microsoft.com/en-us/library/dd305261.aspx https://msdn.microsoft.com/en-us/library/dd303230.aspx
@param w: TdsWriter @param val: TableValuedParam or None @return:
- write_info(w)[source]¶
Writes TVP_TYPENAME structure
spec: https://msdn.microsoft.com/en-us/library/dd302994.aspx @param w: TdsWriter @return:
- class pytds.tds_types.TableType(typ_schema, typ_name, columns)[source]¶
Used to serialize table valued parameters
spec: https://msdn.microsoft.com/en-us/library/dd304813.aspx
- class pytds.tds_types.TableValuedParam(type_name=None, columns=None, rows=None)[source]¶
Used to represent a value of table-valued parameter
- class pytds.tds_types.Text70Serializer(size=0, table_name='', collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0), codec=None)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.Text71Serializer(size=0, table_name='', collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0), codec=None)[source]¶
- class pytds.tds_types.Text72Serializer(size=0, table_name_parts=(), collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0))[source]¶
- class pytds.tds_types.TinyIntSerializer(precision=None, scale=None, size=None)[source]¶
- class pytds.tds_types.UDT72Serializer(max_byte_size, db_name, schema_name, type_name, assembly_qualified_name)[source]¶
- class pytds.tds_types.VarBinarySerializer(size)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.VarBinarySerializerMax[source]¶
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.VarChar70Serializer(size, collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0), codec=None)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.VarChar71Serializer(size, collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0), codec=None)[source]¶
- class pytds.tds_types.VarChar72Serializer(size, collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0), codec=None)[source]¶
- class pytds.tds_types.VarCharMaxSerializer(collation=Collation(lcid=0, sort_id=0, ignore_case=0, ignore_accent=0, ignore_width=0, ignore_kana=0, binary=0, binary2=0, version=0))[source]¶
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
- class pytds.tds_types.VariantSerializer(precision=None, scale=None, size=None)[source]¶
- classmethod from_stream(r)[source]¶
Class method that reads and returns a type instance.
- Parameters:
r – An instance of
_TdsReader
to read type from.
Should be implemented in actual types.
- read(r)[source]¶
Reads value from the stream.
- Parameters:
r – An instance of
_TdsReader
to read value from.- Returns:
A read value.
Should be implemented in actual types.
pytds.tz – timezones¶
- class pytds.tz.FixedOffsetTimezone(offset: float, name: str | None = None)[source]¶
Fixed offset in minutes east from UTC.