Skip to content

Python Database APIs

Jahnvi Thakkar edited this page Aug 7, 2026 · 10 revisions

Following is the consolidated, comprehensive table combining all information about the mssql-python module, covering global attributes, connection management, cursor operations, row handling, exception classes, transaction management, and stored procedure execution:

Global Module APIs & Attributes

API / AttributeTypeDescription
connect(conn_str, autocommit=False, native_uuid=None, token_provider=None)FunctionCreates a Connection object to SQL Server. Per-connection UUID format override via native_uuid. token_provider accepts an Azure Identity credential (any object with a .get_token(scope) method) for Microsoft Entra ID authentication; mutually exclusive with Authentication= and with an attrs_before access token.
apilevelModule attributeDB API spec level supported ("2.0").
paramstyleModule attributeDefault parameter style ("pyformat"). Supports both pyformat (%(name)s) and qmark (?) with automatic detection.
threadsafetyModule attributeThread sharing capability (1: share module, not connections).
lowercaseSettingConverts query column names to lowercase when True.
decimal_separatorSettingCharacter used for parsing DECIMAL/NUMERIC (default ".").
native_uuidSettingIf True (default), returns UUID as uuid.UUID; if False, returns uppercase strings.
get_settings()FunctionReturns global driver settings object.
setDecimalSeparator(separator)FunctionSets decimal separator globally.
getDecimalSeparator()FunctionGets current decimal separator.
pooling(max_size, idle_timeout, enabled)FunctionConfigures client-side connection pooling.
allModule attributeExplicit list of public symbols for static type checker compatibility.

Connection Class

API / AttributeTypeDescription
cursor()MethodCreates and returns a Cursor.
execute(sql, *args)MethodExecutes SQL with a temporary cursor; returns the cursor.
batch_execute(statements, params, ...)MethodEfficient batch execution.
commit()MethodCommits current transaction.
rollback()MethodRolls back current transaction.
close()MethodCloses the connection and frees resources.
closedPropertyRead-only. Returns True if close() was called, False otherwise.
autocommitPropertyTrue when autocommit mode is enabled.
setautocommit(bool)MethodEnables/disables autocommit.
setencoding(encoding, ctype)MethodSets encoding for outgoing SQL.
setdecoding(sqltype, encoding, ctype)MethodSets decoding for incoming text for SQL type.
add_output_converter(sqltype, func)MethodRegisters custom output converter.
get_output_converter(sqltype)MethodRetrieves registered converter or None.
remove_output_converter(sqltype)MethodUnregisters converter.
clear_output_converters()MethodRemoves all converters.
timeoutPropertySQL execution timeout in seconds (0 = disabled).
searchescapePropertyEscape char for LIKE patterns.
Context manager (with)FeatureEnsures cleanup + correct commit/rollback.
Exception exposureFeatureAll DB API exceptions available via connection.
Connection PoolingFeatureBuilt-in client-side pooling.
getinfo()MethodDriver/Database metadata.
getencoding()MethodCurrent text encoding settings
getdecoding()MethodReturns decoding settings for specified SQL type.
set_attr()MethodSets connection attributes.

Cursor Class

APITypeDescription
execute(operation, parameters=None, use_prepare=False)MethodExecutes a SQL statement; supports prepared execution.
executemany(operation, seq_of_parameters)MethodExecutes repeatedly for multiple parameter sets.
fetchone()MethodFetches next row or None.
fetchmany(size=None)MethodFetches batch of rows.
fetchall()MethodFetches all remaining rows.
fetchval()MethodReturns first column of first row.
arrow()MethodFetches all remaining rows as a PyArrow Table.
arrow_batch(size=None)MethodFetches rows as a PyArrow RecordBatch.
arrow_reader()MethodReturns a PyArrow RecordBatchReader for streaming.
nextset()MethodMoves to next result set.
next()MethodAdvances and returns next row (iteration support).
skip(count)MethodSkips N rows.
scroll(value, mode='relative')MethodMoves cursor position.
setinputsizes(sizes)MethodParameter type hints for performance.
close()MethodCloses cursor.
descriptionAttributeColumn metadata (name, type, etc.).
rowcountAttributeRows affected/returned; -1 if unknown.
arraysizeAttributeBatch size for fetchmany().
rownumberAttributeCurrent row index.
messagesAttributeSQL Server PRINT/log messages.
connectionAttributeParent connection.
Streaming supportFeatureEfficient streaming of large varchar(max), nvarchar(max), varbinary(max).

Schema Discovery Functions (Cursor)

API / NameType / FeatureDescription
tables(...)Method (Cursor)Returns metadata on tables matching criteria.
columns(...)Method (Cursor)Returns metadata on columns belonging to specified tables.
statistics(...)Method (Cursor)Returns indexes and statistics info for tables.
rowIdColumns(...)Method (Cursor)Returns columns uniquely identifying rows.
rowVerColumns(...)Method (Cursor)Returns columns automatically updated on row changes.
primaryKeys(...)Method (Cursor)Returns primary key columns of a table.
foreignKeys(...)Method (Cursor)Returns foreign key info of tables.
procedures(...)Method (Cursor)Returns stored procedure metadata.
getTypeInfo(...)Method (Cursor)Returns detailed info about supported SQL types.
Context Manager SupportFeatureCursors support with statement for automatic close (transaction not controlled by cursor).

Row Object

API / NameType / FeatureDescription
Row objectObjectRepresents a single row; supports column access by name or index; iterable. Directly importable: from mssql_python import Row.
cursor_descriptionAttribute (Row)Copy of Cursor.description from the cursor that created the row.
lowercaseAttributeCase-insensitive column access when global lowercase=True

Exception Classes

API / NameType / FeatureDescription
WarningException classGeneral database warnings.
ErrorBase Exception classBase class for all database exceptions.
InterfaceErrorException classDB API interface related errors.
DatabaseErrorException classDatabase related errors.
DataErrorException classData-specific errors (conversion, constraints).
OperationalErrorException classOperational failures (disconnects, timeouts).
IntegrityErrorException classIntegrity constraints violations.
InternalErrorException classInternal driver or DB errors.
ProgrammingErrorException classProgramming errors or SQL syntax issues.
NotSupportedErrorException classUnsupported feature or request.
ConnectionStringParseErrorException classRaised when parsing the connection string fails.
Error Code MappingMechanismMaps SQLSTATE codes to matching exceptions.

Database Transaction Management

API / NameType / FeatureDescription
Database TransactionConceptUnit of SQL work executed atomically.
Autocommit ModeFeatureWhen enabled, each statement commits automatically.
Manual Transaction ManagementFeature (default)Explicit commit / rollback required.
conn.setautocommit(True/False)MethodEnables or disables autocommit mode.
conn.commit() / cursor.commit()MethodCommits all pending changes.
conn.rollback() / cursor.rollback()MethodRolls back all pending changes.
Implicit Transaction StartBehaviorNew transaction starts automatically on connection or after commit/rollback.
No Explicit BEGIN NeededBehaviorNo need for BEGIN TRANSACTION; managed implicitly.
Cursors Do NOT Control TransactionsPrincipleAll cursors share the same transaction on a connection.
Concurrent TransactionsPatternUse separate connections for independent transactions.
Automatic Rollback on CloseBehaviorClosing a connection with uncommitted work triggers rollback.
Connection Context ManagerFeatureUsing with connection: auto-commits on success or rollbacks on exception.

Stored Procedure Execution

API / NameType / FeatureDescription
callproc()Not supportedcallproc() not implemented; use alternatives below.
{CALL ...} / execute()UsageUse ODBC escape syntax in cursor.execute().
Calling without parametersExamplecursor.execute("{CALL usp_NoParameters}")
Calling with input parametersExamplecursor.execute("{CALL usp_UpdateName (?,?)}", (42, "Arthur"))
Output parameters & return valuesPatternUse DECLARE + EXEC with OUTPUT → SELECT; handle via nextset().
Multiple result setsBehaviorRetrieve via fetchall() + nextset() sequence.
Example output parameter retrievalExampleDECLARE var, EXEC with OUTPUT, SELECT var, fetch value.
Example return value retrievalExampleDECLARE return_value, EXEC proc, SELECT return_value, fetchval().

Clone this wiki locally