All pages
Powered by GitBook
1 of 6

API Reference

API Reference

Contents:

  • The MariaDB Connector/Python module

    • Constructors

    • Attributes

    • Exceptions

  • The connection class

    • Connection

    • Connection constructors

    • Connection methods

    • Connection attributes

  • The cursor class

    • Cursor

    • Cursor methods

    • Cursor attributes

  • The ConnectionPool class

    • ConnectionPool

    • ConnectionPool methods

    • ConnectionPool attributes

  • Constants

    • CAPABILITY

    • CLIENT

    • CURSOR

    • ERR (Error)

    • FIELD_FLAG

    • FIELD_TYPE

    • INDICATORS

    • INFO

    • TPC_STATE

    • STATUS

This page is covered by the Creative Commons Attribution 3.0 license.

The MariaDB Connector/Python module

MariaDB Connector/Python module enables python programs to access MariaDB and MySQL databases, using an API which is compliant with the Python DB API 2.0 (PEP-249).

Constructors

Connection

connect(connectionclass=mariadb.connections.Connection, **kwargs)

Creates a MariaDB Connection object.

By default, the standard connectionclass mariadb.connections.Connection will be created.

Parameter connectionclass specifies a subclass of mariadb.Connection object. If not specified, default will be used. This optional parameter was added in version 1.1.0.

Connection parameters are provided as a set of keyword arguments:

  • `host` - The host name or IP address of the database server. If MariaDB Connector/Python was built with MariaDB Connector/C 3.3, it is also possible to provide a comma separated list of hosts for simple fail over in case of one or more hosts are not available.

  • `user`, `username` - The username used to authenticate with the database server

  • `password`, `passwd` - The password of the given user

  • `database`, `db` - Database (schema) name to use when connecting with the database server

  • `unix_socket` - The location of the unix socket file to use instead of using an IP port to connect. If socket authentication is enabled, this can also be used in place of a password.

  • `port` - Port number of the database server. If not specified, the default value of 3306 will be used.

  • `connect_timeout` - Connect timeout in seconds

  • `read_timeout` - Read timeout in seconds

  • `write_timeout` - Write timeout in seconds

  • `local_infile` - Enables or disables the use of LOAD DATA LOCAL INFILE statements.

  • `compress` (default: False) - Uses the compressed protocol for client server communication. If the server doesn’t support compressed protocol, the default protocol will be used.

  • `init_command` - Command(s) which will be executed when connecting and reconnecting to the database server

  • `default_file` - Read options from the specified option file. If the file is an empty string, default configuration file(s) will be used

  • `default_group` - Read options from the specified group

  • `plugin_dir` - Directory which contains MariaDB client plugins.

  • `reconnect` - Enables or disables automatic reconnect. Available since version 1.1.4

  • `ssl_key` - Defines a path to a private key file to use for TLS. This option requires that you use the absolute path, not a relative path. The specified key must be in PEM format

  • `ssl_cert` - Defines a path to the X509 certificate file to use for TLS. This option requires that you use the absolute path, not a relative path. The X609 certificate must be in PEM format.

  • `ssl_ca` - Defines a path to a PEM file that should contain one or more X509 certificates for trusted Certificate Authorities (CAs) to use for TLS. This option requires that you use the absolute path, not a relative path.

  • `ssl_capath` - Defines a path to a directory that contains one or more PEM files that contains one X509 certificate for a trusted Certificate Authority (CA)

  • `ssl_cipher` - Defines a list of permitted cipher suites to use for TLS

  • `ssl_crlpath` - Defines a path to a PEM file that should contain one or more revoked X509 certificates to use for TLS. This option requires that you use the absolute path, not a relative path.

  • `ssl_verify_cert` - Enables server certificate verification.

  • `ssl` - The connection must use TLS security, or it will fail.

  • `tls_version` - A comma-separated list (without whitespaces) of TLS versions. Valid versions are TLSv1.0, TLSv1.1,TLSv1.2 and TLSv1.3. Added in version 1.1.7.

  • `autocommit` (default: False) - Specifies the autocommit settings. True will enable autocommit, False will disable it (default).

  • `converter` - Specifies a conversion dictionary, where keys are FIELD_TYPE values and values are conversion functions

NOTE

For a description of configuration file handling and settings please read the chapter Configuration files of the MariaDB Connector/C documentation.

Example:

import mariadb

with mariadb.connect(user="example_user", host="localhost", database="test", password="GHbe_Su3B8") as connection:
    print(connection.character_set)

Output:

utf8mb4

Connection Pool

ConnectionPool(**kwargs)

Class defining a pool of database connections

MariaDB Connector/Python supports simple connection pooling. A connection pool holds a number of open connections and handles thread safety when providing connections to threads.

The size of a connection pool is configurable at creation time, but cannot be changed afterward. The maximum size of a connection pool is limited to 64 connections.

Keyword Arguments:

  • `pool_name` (str) - Name of connection pool

  • `pool_size` (int) - Size of pool. The Maximum allowed number is 64. Default to 5

  • `pool_reset_connection` (bool) - Will reset the connection before returning it to the pool. Default to True.

  • `pool_validation_interval` (int) - Specifies the validation interval in milliseconds after which the status of a connection requested from the pool is checked. A value of 0 means that the status will always be checked. Default to 500 (Added in version 1.1.6)

  • **kwargs - Optional additional connection arguments, as described in mariadb.connect() method.

Type constructors

Binary()

Constructs an object capable of holding a binary value.

Date(year, month, day)

Constructs an object holding a date value.

DateFromTicks(ticks)

Constructs an object holding a date value from the given ticks value (number of seconds since the epoch). For more information see the documentation of the standard Python time module.

Time(hour, minute, second)

Constructs an object holding a time value.

TimeFromTicks(ticks)

Constructs an object holding a time value from the given ticks value (number of seconds since the epoch). For more information see the documentation of the standard Python time module.

Timestamp(year, month, day, hour, minute, second)

Constructs an object holding a datetime value.

TimestampFromTicks(ticks)

Constructs an object holding a datetime value from the given ticks value (number of seconds since the epoch). For more information see the documentation of the standard Python time module.

Attributes

apilevel

String constant stating the supported DB API level. The value for mariadb is 2.0.

threadsafety

Integer constant stating the level of thread safety. For mariadb the value is 1, which means threads can share the module but not the connection.

paramstyle

String constant stating the type of parameter marker. For mariadb the value is qmark. For compatibility reasons mariadb also supports the format and pyformat paramstyles with the limitation that they can’t be mixed inside a SQL statement.

mariadbapi_version

String constant stating the version of the used MariaDB Connector/C library.

client_version

Since version 1.1.0

Returns the version of MariaDB Connector/C library in use as an integer. The number has the following format: MAJOR_VERSION * 10000 + MINOR_VERSION * 1000 + PATCH_VERSION

client_version_info

Since version 1.1.0 Returns the version of MariaDB Connector/C library as a tuple in the following format: (MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION)

Exceptions

Compliant to DB API 2.0 MariaDB Connector/C provides information about errors through the following exceptions:

exception DataError

Exception raised for errors that are due to problems with the processed data like division by zero, numeric value out of range, etc.

exception DatabaseError

Exception raised for errors that are related to the database

exception InterfaceError

Exception raised for errors that are related to the database interface rather than the database itself

exception Warning

Exception raised for important warnings like data truncations while inserting, etc

exception PoolError

Exception raised for errors related to ConnectionPool class.

exception OperationalError

Exception raised for errors that are related to the database’s operation and not necessarily under the control of the programmer.

exception IntegrityError

Exception raised when the relational integrity of the database is affected, e.g. a foreign key check fails

exception InternalError

Exception raised when the database encounters an internal error, e.g. the cursor is not valid anymore

exception ProgrammingError

Exception raised for programming errors, e.g. table not found or already exists, syntax error in the SQL statement

exception NotSupportedError

Exception raised in case a method or database API was used which is not supported by the database

Type objects

MariaDB Connector/Python type objects are immutable sets for type settings and defined in DBAPI 2.0 (PEP-249).

Example:

import mariadb
from mariadb.constants import FIELD_TYPE

print(FIELD_TYPE.GEOMETRY == mariadb.BINARY)
print(FIELD_TYPE.DATE == mariadb.DATE)
print(FIELD_TYPE.VARCHAR == mariadb.BINARY)

Output:

True
True
False

STRING

This type object is used to describe columns in a database that are string-based (e.g. CHAR1).

BINARY

This type object is used to describe (long) binary columns in a database (e.g. LONG, RAW, BLOBs).

NUMBER

This type object is used to describe numeric columns in a database.

DATETIME

This type object is used to describe date/time columns in a database.

ROWID

This type object is not supported in MariaDB Connector/Python and represents an empty set.

This page is covered by the Creative Commons Attribution 3.0 license.

The connection class

class Connection(*args, **kwargs)

MariaDB Connector/Python Connection Object

Handles the connection to a MariaDB or MySQL database server. It encapsulates a database session.

Connections are created using the method mariadb.connect()

Connection constructors

Connection.xid(format_id: int, global_transaction_id: str, branch_qualifier: str)

Creates a transaction ID object suitable for passing to the .tpc_*() methods of this connection.

Parameters:

  • format_id: Format id. Default to value 0.

  • global_transaction_id: Global transaction qualifier, which must be unique. The maximum length of the global transaction id is limited to 64 characters.

  • branch_qualifier: Branch qualifier which represents a local transaction identifier. The maximum length of the branch qualifier is limited to 64 characters.

Since version 1.0.1.

Connection methods

Connection.begin()

Start a new transaction which can be committed by .commit() method, or canceled by .rollback() method.

Since version 1.1.0.

Connection.commit()

Commit any pending transaction to the database.

Connection.change_user()

Changes the user and default database of the current connection

Parameters: : - user: user name

  • password: password

  • database: name of default database

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails an exception will be raised and the current user authentication will remain.

Connection.close()

Close the connection now (rather than whenever ._del_() is called).

The connection will be unusable from this point forward; an Error (or subclass) exception will be raised if any operation is attempted with the connection. The same applies to all cursor objects trying to use the connection.

Note that closing a connection without committing the changes first will cause an implicit rollback to be performed.

Connection.cursor(cursorclass=<class 'mariadb.cursors.Cursor'>, **kwargs)

Returns a new cursor object for the current connection.

If no cursorclass was specified, a cursor with default mariadb.Cursor class will be created.

Optional keyword parameters:

  • buffered (default: True) - If disabled, the result will be unbuffered, which means before executing another statement with the same connection, the entire result set must be fetched. Please note that the default was False for MariaDB Connector/Python versions < 1.1.0.

  • dictionary (default: False) - Return fetch values as dictionary when enabled.

  • named_tuple (default: False) - Return fetch values as named tuple. This feature exists for compatibility reasons and should be avoided due to possible inconsistency.

  • cursor_type (default: CURSOR.NONE) - If cursor_type is set to CURSOR.READ_ONLY, a cursor is opened for the statement invoked with cursors execute() method.

  • prepared (default: False) - When enabled, the cursor will remain in prepared state after the first execute() method was called. Further calls to execute() method will ignore the SQL statement.

  • binary (default: False) - Always execute statement in MariaDB client/server binary protocol.

In versions prior to 1.1.0 results were unbuffered by default, which means before executing another statement with the same connection, the entire result set must be fetched.

fetch* methods of the cursor class by default return result set values as a tuple, unless dictionary or named_tuple was specified. The latter one exists for compatibility reasons and should be avoided due to possible inconsistency in case two or more fields in a result set have the same name.

If cursor_type is set to CURSOR.READ_ONLY, a cursor is opened for the statement invoked with cursors execute() method.

Connection.dump_debug_info()

This function is designed to be executed by an user with the SUPER privilege and is used to dump server status information into the log for the MariaDB Server relating to the connection.

Since version 1.1.2.

Connection.get_server_version()

Returns a tuple representing the version of the connected server in the following format: (MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION)

Connection.escape_string()

Parameters: statement: string

This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string.

Since version 1.0.5.

# connection parameters
conn_params= {
    "user" : "example_user",
    "password" : "GHbe_Su3B8",
    "host" : "localhost"
}

with mariadb.connect(**conn_params) as connection:
    string = 'This string contains the following special characters: \\,"'
    print(connection.escape_string(string))

Output:

This string contains the following special characters: \\,\"

Connection.kill(id: int)

This function is used to ask the server to kill a database connection specified by the processid parameter.

The connection id can be retrieved by SHOW PROCESSLIST SQL command.

NOTE

A thread_id from other connections can be determined by executing the SQL statement SHOW PROCESSLIST. The thread_id of the current connection is stored in the connection_id attribute.

Connection.ping()

Checks if the connection to the database server is still available.

If auto reconnect was set to true, an attempt will be made to reconnect to the database server in case the connection was lost

If the connection is not available an InterfaceError will be raised.

Connection.reconnect()

tries to reconnect to a server in case the connection died due to timeout or other errors. It uses the same credentials which were specified in connect() method.

Connection.reset()

Resets the current connection and clears session state and pending results. Open cursors will become invalid and cannot be used anymore.

Connection.rollback()

Causes the database to roll back to the start of any pending transaction

Closing a connection without committing the changes first will cause an implicit rollback to be performed. Note that rollback() will not work as expected if autocommit mode was set to True or the storage engine does not support transactions.”

Connection.select_db(new_db: str)

Gets the default database for the current connection.

The default database can also be obtained or changed by database attribute.

Since version 1.1.0.

Connection.show_warnings()

Shows error, warning and note messages from last executed command.

Connection.tpc_begin(xid)

Parameter: : xid: xid object which was created by .xid() method of connection : class

Begins a TPC transaction with the given transaction ID xid.

This method should be called outside a transaction (i.e., nothing may have been executed since the last .commit() or .rollback()). Furthermore, it is an error to call .commit() or .rollback() within the TPC transaction. A ProgrammingError is raised if the application calls .commit() or .rollback() during an active TPC transaction.

Connection.tpc_commit(xid=None)

Optional parameter:

  • xid : xid object which was created by .xid() method of connection class.

When called with no arguments, .tpc_commit() commits a TPC transaction previously prepared with .tpc_prepare().

If .tpc_commit() is called prior to .tpc_prepare(), a single phase commit is performed. A transaction manager may choose to do this if only a single resource is participating in the global transaction. When called with a transaction ID xid, the database commits the given transaction. If an invalid transaction ID is provided, a ProgrammingError will be raised. This form should be called outside a transaction, and is intended for use in recovery.

Connection.tpc_prepare()

Performs the first phase of a transaction started with .tpc_begin(). A ProgrammingError will be raised if this method was called outside a TPC transaction.

After calling .tpc_prepare(), no statements can be executed until .tpc_commit() or .tpc_rollback() have been called.

Connection.tpc_recover()

Returns a list of pending transaction IDs suitable for use with tpc_commit(xid) or .tpc_rollback(xid).

Connection.tpc_rollback(xid=None)

Parameter: : xid: xid object which was created by .xid() method of connection : class

Performs the first phase of a transaction started with .tpc_begin(). A ProgrammingError will be raised if this method outside a TPC transaction.

After calling .tpc_prepare(), no statements can be executed until .tpc_commit() or .tpc_rollback() have been called.

Connection attributes

Connection.auto_reconnect

(read/write)

Enable or disable automatic reconnection to the server if the connection is found to have been lost.

When enabled, client tries to reconnect to a database server in case the connection to a database server died due to timeout or other errors.

Connection.autocommit

Toggles autocommit mode on or off for the current database connection.

Autocommit mode only affects operations on transactional table types. Be aware that rollback() will not work if autocommit mode was switched on.

By default, autocommit mode is set to False.

Connection.character_set

Client character set.

For MariaDB Connector/Python, it is always utf8mb4.

Connection.client_capabilities

Client capability flags.

Since version 1.1.0.

Connection.collation

Client character set collation

Connection.connection_id

Id of current connection

Connection.database

Get the current database of the connection.

Connection.open

Returns true if the connection is alive.

A ping command will be sent to the server for this purpose, which means this function might fail if there are still non-processed pending result sets.

Since version 1.1.0.

Connection.server_capabilities

Server capability flags.

Since version 1.1.0.

Connection.extended_server_capabilities

Extended server capability flags (only for MariaDB database servers).

Since version 1.1.0.

Connection.server_info

Server version in alphanumerical format (str)

Connection.server_name

Name or IP address of database server.

Connection.server_port

Database server TCP/IP port. This value will be 0 in case of an unix socket connection.

Connection.server_status

Return server status flags

Since version 1.1.0.

Connection.server_version

Server version in numerical format.

The form of the version number is VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_PATCH

Connection.server_version_info

Returns numeric version of connected database server in tuple format.

Connection.tls_cipher

TLS cipher suite if a secure connection is used.

Since version 1.0.5.

Connection.tls_version

TLS protocol version if a secure connection is used.

Connection.tls_peer_cert_info

Get peer certificate information.

Since version 1.1.11.

Connection.unix_socket

Unix socket name.

Connection.user

Returns the username for the current connection or empty string if it can’t be determined, e.g., when using socket authentication.

Connection.warnings

Returns the number of warnings from the last executed statement, or zero if there are no warnings.

This page is covered by the Creative Commons Attribution 3.0 license.

The cursor class

class Cursor(connection, **kwargs)

MariaDB Connector/Python Cursor Object

Cursor methods

Cursor.callproc(sp: str, data: Sequence = ())

Executes a stored procedure sp. The data sequence must contain an entry for each parameter the procedure expects.

Input/Output or Output parameters have to be retrieved by .fetch methods, the .sp_outparams attribute indicates if the result set contains output parameters.

Arguments: : - sp: Name of stored procedure.

  • data: Optional sequence containing data for placeholder : substitution.

Example:

>>>cursor.execute("CREATE PROCEDURE p1(IN i1 VAR  CHAR(20), OUT o2 VARCHAR(40))"
                  "BEGIN"
                  "  SELECT 'hello'"
                  "  o2:= 'test'"
                  "END")
>>>cursor.callproc('p1', ('foo', 0))
>>> cursor.sp_outparams
False
>>> cursor.fetchone()
('hello',)
>>> cursor.nextset()
True
>>> cursor.sp_outparams
True
>>> cursor.fetchone()
('test',)

Cursor.execute(statement: str, data: Sequence = (), buffered=None)

Prepare and execute a SQL statement.

Parameters may be provided as sequence or mapping and will be bound to variables in the operation. Variables are specified as question marks (paramstyle =’qmark’), however for compatibility reasons MariaDB Connector/Python also supports the ‘format’ and ‘pyformat’ paramstyles with the restriction, that different paramstyles can’t be mixed within a statement.

A reference to the operation will be retained by the cursor. If the cursor was created with attribute prepared =True the statement string for following execute operations will be ignored. This is most effective for algorithms where the same operation is used, but different parameters are bound to it (many times).

By default execute() method generates an buffered result unless the optional parameter buffered was set to False or the cursor was generated as an unbuffered cursor.

Cursor.executemany(statement, parameters)

Prepare a database operation (INSERT,UPDATE,REPLACE or DELETE statement) and execute it against all parameter found in sequence.

Exactly behaves like .execute() but accepts a list of tuples, where each tuple represents data of a row within a table. .executemany() only supports DML (insert, update, delete) statements.

If the SQL statement contains a RETURNING clause, executemany() returns a result set containing the values for columns listed in the RETURNING clause.

Example:

The following example will insert 3 rows:

data= [
    (1, 'Michael', 'Widenius')
    (2, 'Diego', 'Dupin')
    (3, 'Lawrin', 'Novitsky')
]
cursor.executemany("INSERT INTO colleagues VALUES (?, ?, ?)", data)

To insert special values like NULL or a column default, you need to specify indicators:

  • INDICATOR.NULL is used for NULL values

  • INDICATOR.IGNORE is used to skip update of a column.

  • INDICATOR.DEFAULT is used for a default value (insert/update)

  • INDICATOR.ROW is used to skip update/insert of the entire row.

NOTE

  • All values for a column must have the same data type.

  • Indicators can only be used when connecting to a MariaDB Server 10.2 or newer. MySQL servers don’t support this feature.

Cursor.fetchall()

Fetch all remaining rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples).

An exception will be raised if the previous call to execute() didn’t produce a result set or execute() wasn’t called before.

Cursor.fetchmany(size: int = 0)

Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available.

The number of rows to fetch per call is specified by the parameter. If it is not given, the cursor’s arraysize determines the number of rows to be fetched. The method should try to fetch as many rows as indicated by the size parameter. If this is not possible due to the specified number of rows not being available, fewer rows may be returned.

An exception will be raised if the previous call to execute() didn’t produce a result set or execute() wasn’t called before.

Cursor.fetchone()

Fetch the next row of a query result set, returning a single sequence, or None if no more data is available.

An exception will be raised if the previous call to execute() didn’t produce a result set or execute() wasn’t called before.

Cursor.next()

Return the next row from the currently executed SQL statement using the same semantics as .fetchone().

Cursor.nextset()

Will make the cursor skip to the next available result set, discarding any remaining rows from the current set.

Cursor.scroll(value: int, mode='relative')

Scroll the cursor in the result set to a new position according to mode.

If mode is “relative” (default), value is taken as offset to the current position in the result set, if set to absolute, value states an absolute target position.

Cursor.setinputsizes()

Required by PEP-249. Does nothing in MariaDB Connector/Python

Cursor.setoutputsize()

Required by PEP-249. Does nothing in MariaDB Connector/Python

Cursor attributes

Cursor.arraysize

(read/write)

the number of rows to fetch

This read/write attribute specifies the number of rows to fetch at a time with .fetchmany(). It defaults to 1 meaning to fetch a single row at a time

Cursor.buffered

When True all result sets are immediately transferred and the connection between client and server is no longer blocked. Since version 1.1.0 default is True, for prior versions default was False.

Cursor.closed

Indicates if the cursor is closed and can’t be reused

Cursor.connection

Read-Only attribute which returns the reference to the connection object on which the cursor was created.

Cursor.description

This read-only attribute is a sequence of 11-item sequences Each of these sequences contains information describing one result column:

  • name

  • type_code

  • display_size

  • internal_size

  • precision

  • scale

  • null_ok

  • field_flags

  • table_name

  • original_column_name

  • original_table_name

This attribute will be None for operations that do not return rows or if the cursor has not had an operation invoked via the .execute*() method yet.

NOTE

The 8th parameter ‘field_flags’ is an extension to the PEP-249 DB API standard. In combination with the type element field, it can be determined for example, whether a column is a BLOB or TEXT field:

Since version 1.1.0

The parameter table_name, original_column_name and original_table_name are an extension to the PEP-249 DB API standard.

if cursor.description[0][1] == FIELD_TYPE.BLOB:
    if cursor.description[0][7] == FIELD_FLAG.BINARY:
        print("column is BLOB")
    else:
        print("column is TEXT")

Cursor.lastrowid

Returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute or the value for the last usage of LAST_INSERT_ID().

If the last query wasn’t an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute and LAST_INSERT_ID was not used, the returned value will be None

Cursor.metadata

Similar to description property, this property returns a dictionary with complete metadata.

The dictionary contains the following keys:

  • catalog: catalog (always ‘def’)

  • schema: current schema

  • field: alias column name or if no alias was specified column name

  • org_field: original column name

  • table: alias table name or if no alias was specified table name

  • org_table: original table name

  • type: column type

  • charset: character set (utf8mb4 or binary)

  • length: The length of the column

  • max length: The maximum length of the column

  • decimals: The numer of decimals

  • flags: Flags (flags are defined in constants.FIELD_FLAG)

  • ext_type: Extended data type (types are defined in constants.EXT_FIELD_TYPE)

Since version 1.1.8

Cursor.sp_outparams

Indicates if the current result set contains in out or out parameter from a previous executed stored procedure

Cursor.paramcount

(read)

Returns the number of parameter markers present in the executed statement.

Since version 1.1.0

Cursor.rowcount

This read-only attribute specifies the number of rows that the last execute*() produced (for DQL statements like SELECT) or affected (for DML statements like UPDATE or INSERT). The return value is -1 in case no .execute*() has been performed on the cursor or the rowcount of the last operation cannot be determined by the interface.

NOTE

For unbuffered cursors (default) the exact number of rows can only be determined after all rows were fetched.

Example:

>>> cursor=conn.cursor()
>>> cursor.execute("SELECT 1")
>>> cursor.rowcount
-1
>>> rows= cursor.fetchall()
>>> cursor.rowcount
1
>>> cursor=conn.cursor(buffered=True)
>>> cursor.execute("SELECT 1")
>>> cursor.rowcount
1

Cursor.statement

(read only)

The last executed statement

Cursor.warnings

Returns the number of warnings from the last executed statement, or zero if there are no warnings.

NOTE

Warnings can be retrieved by the show_warnings() method of connection class.

This page is covered by the Creative Commons Attribution 3.0 license.

The ConnectionPool class

class ConnectionPool(*args, **kwargs)

Class defining a pool of database connections

MariaDB Connector/Python supports simple connection pooling. A connection pool holds a number of open connections and handles thread safety when providing connections to threads.

The size of a connection pool is configurable at creation time, but cannot be changed afterward. The maximum size of a connection pool is limited to 64 connections.

Keyword Arguments:

  • `pool_name` (str) - Name of connection pool

  • `pool_size` (int) - Size of pool. The Maximum allowed number is 64. Default to 5

  • `pool_reset_connection` (bool) - Will reset the connection before returning it to the pool. Default to True.

  • `pool_validation_interval` (int) - Specifies the validation interval in milliseconds after which the status of a connection requested from the pool is checked. A value of 0 means that the status will always be checked. Default to 500 (Added in version 1.1.6)

  • **kwargs - Optional additional connection arguments, as described in mariadb.connect() method.

ConnectionPool methods

ConnectionPool.add_connection(connection=None)

Adds a connection object to the connection pool.

In case that the pool doesn’t have a free slot or is not configured, a PoolError exception will be raised.

ConnectionPool.close()

Closes connection pool and all connections.

ConnectionPool.get_connection()

Returns a connection from the connection pool or raises a PoolError exception if a connection is not available.

ConnectionPool.set_config(**kwargs)

Sets the connection configuration for the connection pool. For valid connection arguments, check the mariadb.connect() method.

Note: This method doesn’t create connections in the pool. To fill the pool, one has to use add_connection() ḿethod.

ConnectionPool attributes

ConnectionPool.connection_count

Returns the number of connections in connection pool.

Since version 1.1.0

ConnectionPool.max_size

Returns the maximum size for connection pools.

ConnectionPool.pool_size

Returns the size of the connection pool.

ConnectionPool.pool_name

Returns the name of the connection pool.

This page is covered by the Creative Commons Attribution 3.0 license.

Constants

Constants are declared in mariadb.constants module.

For using constants of various types, they have to be imported first:

from mariadb.constants import *

CAPABILITY

MariaDB capability flags.

These flags are used to check the capabilities both of a MariaDB server or the client applicaion.

Capability flags are defined in module mariadb.constants.CAPABILIY

Since version 1.1.4

import mariadb
from mariadb.constants import *

# connection parameters
conn_params= {
    "user" : "example_user",
    "password" : "GHbe_Su3B8",
    "host" : "localhost"
}

with mariadb.connect(**conn_params) as connection:
    # test if LOAD DATA LOCAL INFILE is supported
    if connection.server_capabilities & CAPABILITY.LOCAL_FILES:
        print("Server supports LOCAL INFILE")

Output:

Server supports LOCAL INFILE

CLIENT

MariaDB capability flags.

These flags are used to check the capabilities both of a MariaDB server or the client applicaion.

Capability flags are defined in module mariadb.constants.CLIENT

Since version 1.1.0, deprecated in 1.1.4

CURSOR

Cursor constants are used for server side cursors. Currently only read only cursor is supported.

Cursor constants are defined in module mariadb.constants.CURSOR.

Since version 1.1.0

CURSOR.NONE

This is the default setting (no cursor)

CURSOR.READ_ONLY

Will create a server side read only cursor. The cursor is a forward cursor, which means it is not possible to scroll back.

ERR (Error)

Using ERR constants instead of error numbers make the code more readable. Error constants are defined in constants.ERR module

Since version 1.1.2

import mariadb
from mariadb.constants import *

# connection parameters
conn_params= {
    "user" : "example_user",
    "password" : "wrong_password",
    "host" : "localhost"
}

# try to establish a connection
try:
    connection= mariadb.connect(**conn_params)
except mariadb.OperationalError as Err:
    if Err.errno == ERR.ER_ACCESS_DENIED_ERROR:
        print("Access denied. Wrong password!")

Output:

Access denied. Wrong password!

FIELD_FLAG

MariaDB FIELD_FLAG Constants

These constants represent the various field flags. As an addition to the DBAPI 2.0 standard (PEP-249) these flags are returned as eighth element of the cursor description attribute.

Field flags are defined in module mariadb.constants.FIELD_FLAG

Since version 1.1.0

FIELD_FLAG.NOT_NULL

column is defined as not NULL

FIELD_FLAG.PRIMARY_KEY

column is (part of) a primary key

FIELD_FLAG.UNIQUE_KEY

column is (part of) a unique key

FIELD_FLAG.MULTIPLE_KEY

column is (part of) a key

FIELD_FLAG.BLOB

column contains a binary object

FIELD_FLAG.UNSIGNED

numeric column is defined as unsigned

FIELD_FLAG.ZEROFILL

column has zerofill attribute

FIELD_FLAG.BINARY

column is a binary

FIELD_FLAG.ENUM

column is defined as enum

FIELD_FLAG.AUTO_INCREMENT

column is an auto_increment column

FIELD_FLAG.TIMESTAMP

column is defined as time stamp

FIELD_FLAG.SET

column is defined as SET

FIELD_FLAG.NO_DEFAULT

column hasn’t a default value

FIELD_FLAG.ON_UPDATE_NOW

column will be set to current timestamp on UPDATE

FIELD_FLAG.NUMERIC

column contains numeric value

FIELD_FLAG.PART_OF_KEY

column is part of a key

FIELD_TYPE

MariaDB FIELD_TYPE Constants

These constants represent the field types supported by MariaDB. The field type is returned as second element of cursor description attribute.

Field types are defined in module mariadb.constants.FIELD_TYPE

FIELD_TYPE.TINY

column type is TINYINT (1-byte integer)

FIELD_TYPE.SHORT

column type is SMALLINT (2-byte integer)

FIELD_TYPE.LONG

column tyoe is INT (4-byte integer)

FIELD_TYPE.FLOAT

column type is FLOAT (4-byte single precision)

FIELD_TYPE.DOUBLE

column type is DOUBLE (8-byte double precision)

FIELD_TYPE.NULL

column type is NULL

FIELD_TYPE.TIMESTAMP

column tyoe is TIMESTAMP

FIELD_TYPE.LONGLONG

column tyoe is BIGINT (8-byte Integer)

FIELD_TYPE.INT24

column type is MEDIUMINT (3-byte Integer)

FIELD_TYPE.DATE

column type is DATE

FIELD_TYPE.TIME

column type is TIME

FIELD_TYPE.DATETIME

column type is YEAR

FIELD_TYPE.YEAR

FIELD_TYPE.VARCHAR

column type is YEAR

FIELD_TYPE.BIT

column type is BIT

FIELD_TYPE.JSON

column type is JSON

FIELD_TYPE.NEWDECIMAL

column type is DECIMAL

FIELD_TYPE.ENUM

column type is ENUM

FIELD_TYPE.SET

column type is SET

FIELD_TYPE.TINY_BLOB

column type is TINYBLOB (max. length of 255 bytes)

FIELD_TYPE.MEDIUM_BLOB

column type is MEDIUMBLOB (max. length of 16,777,215 bytes)

FIELD_TYPE.LONG_BLOB

column type is LONGBLOB (max. length 4GB bytes)

FIELD_TYPE.BLOB

column type is BLOB (max. length of 65.535 bytes)

FIELD_TYPE.VAR_STRING

column type is VARCHAR (variable length)

FIELD_TYPE.STRING

column type is CHAR (fixed length)

FIELD_TYPE.GEOMETRY

column type is GEOMETRY

INDICATORS

Indicator values are used in executemany() method of cursor class to indicate special values when connected to a MariaDB server 10.2 or newer.

INDICATOR.NULL

indicates a NULL value

INDICATOR.DEFAULT

indicates to use default value of column

INDICATOR.IGNORE

indicates to ignore value for column for UPDATE statements. If set, the column will not be updated.

INDICATOR.IGNORE_ROW

indicates not to update the entire row.

INFO

For internal use only

TPC_STATE

For internal use only

STATUS

The STATUS constants are used to check the server status of the current connection.

Since version 1.1.0

Example:

cursor.callproc("my_storedprocedure", (1,"foo"))

if (connection.server_status & STATUS.SP_OUT_PARAMS): print("retrieving output parameters from store procedure") ... else: print("retrieving data from stored procedure") ....

STATUS.IN_TRANS

Pending transaction

STATUS.AUTOCOMMIT

Server operates in autocommit mode

STATUS.MORE_RESULTS_EXIST

The result from last executed statement contained two or more result sets which can be retrieved by cursors nextset() method.

STATUS.QUERY_NO_GOOD_INDEX_USED

The last executed statement didn’t use a good index.

STATUS.QUERY_NO_INDEX_USED

The last executed statement didn’t use an index.

STATUS.CURSOR_EXISTS

The last executed statement opened a server side cursor.

STATUS.LAST_ROW_SENT

For server side cursors this flag indicates end of a result set.

STATUS.DB_DROPPED

The current database in use was dropped and there is no default database for the connection anymore.

STATUS.NO_BACKSLASH_ESCAPES

Indicates that SQL mode NO_BACKSLASH_ESCAPE is active, which means that the backslash character ‘' becomes an ordinary character.

STATUS.QUERY_WAS_SLOW

The previously executed statement was slow (and needs to be optimized).

STATUS.PS_OUT_PARAMS

The current result set contains output parameters of a stored procedure.

STATUS.SESSION_STATE_CHANGED

The session status has been changed.

STATUS.ANSI_QUOTES

SQL mode ANSI_QUOTES is active,

This page is covered by the Creative Commons Attribution 3.0 license.