Chapter 10 Connector/Python API Reference

Table of Contents

10.1 mysql.connector Module
10.1.1 mysql.connector.connect() Method
10.1.2 mysql.connector.apilevel Property
10.1.3 mysql.connector.paramstyle Property
10.1.4 mysql.connector.threadsafety Property
10.1.5 mysql.connector.__version__ Property
10.1.6 mysql.connector.__version_info__ Property
10.2 connection.MySQLConnection Class
10.2.1 connection.MySQLConnection() Constructor
10.2.2 MySQLConnection.close() Method
10.2.3 MySQLConnection.commit() Method
10.2.4 MySQLConnection.config() Method
10.2.5 MySQLConnection.connect() Method
10.2.6 MySQLConnection.cursor() Method
10.2.7 MySQLConnection.cmd_change_user() Method
10.2.8 MySQLConnection.cmd_debug() Method
10.2.9 MySQLConnection.cmd_init_db() Method
10.2.10 MySQLConnection.cmd_ping() Method
10.2.11 MySQLConnection.cmd_process_info() Method
10.2.12 MySQLConnection.cmd_process_kill() Method
10.2.13 MySQLConnection.cmd_query() Method
10.2.14 MySQLConnection.cmd_query_iter() Method
10.2.15 MySQLConnection.cmd_quit() Method
10.2.16 MySQLConnection.cmd_refresh() Method
10.2.17 MySQLConnection.cmd_reset_connection() Method
10.2.18 MySQLConnection.cmd_shutdown() Method
10.2.19 MySQLConnection.cmd_statistics() Method
10.2.20 MySQLConnection.disconnect() Method
10.2.21 MySQLConnection.get_row() Method
10.2.22 MySQLConnection.get_rows() Method
10.2.23 MySQLConnection.get_server_info() Method
10.2.24 MySQLConnection.get_server_version() Method
10.2.25 MySQLConnection.is_connected() Method
10.2.26 MySQLConnection.isset_client_flag() Method
10.2.27 MySQLConnection.ping() Method
10.2.28 MySQLConnection.reconnect() Method
10.2.29 MySQLConnection.reset_session() Method
10.2.30 MySQLConnection.rollback() Method
10.2.31 MySQLConnection.set_charset_collation() Method
10.2.32 MySQLConnection.set_client_flags() Method
10.2.33 MySQLConnection.shutdown() Method
10.2.34 MySQLConnection.start_transaction() Method
10.2.35 MySQLConnection.autocommit Property
10.2.36 MySQLConnection.can_consume_results Property
10.2.37 MySQLConnection.charset Property
10.2.38 MySQLConnection.collation Property
10.2.39 MySQLConnection.connection_id Property
10.2.40 MySQLConnection.database Property
10.2.41 MySQLConnection.get_warnings Property
10.2.42 MySQLConnection.in_transaction Property
10.2.43 MySQLConnection.raise_on_warnings Property
10.2.44 MySQLConnection.server_host Property
10.2.45 MySQLConnection.server_port Property
10.2.46 MySQLConnection.sql_mode Property
10.2.47 MySQLConnection.time_zone Property
10.2.48 MySQLConnection.unix_socket Property
10.2.49 MySQLConnection.user Property
10.3 pooling.MySQLConnectionPool Class
10.3.1 pooling.MySQLConnectionPool Constructor
10.3.2 MySQLConnectionPool.add_connection() Method
10.3.3 MySQLConnectionPool.get_connection() Method
10.3.4 MySQLConnectionPool.set_config() Method
10.3.5 MySQLConnectionPool.pool_name Property
10.4 pooling.PooledMySQLConnection Class
10.4.1 pooling.PooledMySQLConnection Constructor
10.4.2 PooledMySQLConnection.close() Method
10.4.3 PooledMySQLConnection.config() Method
10.4.4 PooledMySQLConnection.pool_name Property
10.5 cursor.MySQLCursor Class
10.5.1 cursor.MySQLCursor Constructor
10.5.2 MySQLCursor.callproc() Method
10.5.3 MySQLCursor.close() Method
10.5.4 MySQLCursor.execute() Method
10.5.5 MySQLCursor.executemany() Method
10.5.6 MySQLCursor.fetchall() Method
10.5.7 MySQLCursor.fetchmany() Method
10.5.8 MySQLCursor.fetchone() Method
10.5.9 MySQLCursor.fetchwarnings() Method
10.5.10 MySQLCursor.stored_results() Method
10.5.11 MySQLCursor.column_names Property
10.5.12 MySQLCursor.description Property
10.5.13 MySQLCursor.lastrowid Property
10.5.14 MySQLCursor.rowcount Property
10.5.15 MySQLCursor.statement Property
10.5.16 MySQLCursor.with_rows Property
10.6 Subclasses cursor.MySQLCursor
10.6.1 cursor.MySQLCursorBuffered Class
10.6.2 cursor.MySQLCursorRaw Class
10.6.3 cursor.MySQLCursorBufferedRaw Class
10.6.4 cursor.MySQLCursorDict Class
10.6.5 cursor.MySQLCursorBufferedDict Class
10.6.6 cursor.MySQLCursorNamedTuple Class
10.6.7 cursor.MySQLCursorBufferedNamedTuple Class
10.6.8 cursor.MySQLCursorPrepared Class
10.7 constants.ClientFlag Class
10.8 constants.FieldType Class
10.9 constants.SQLMode Class
10.10 constants.CharacterSet Class
10.11 constants.RefreshOption Class
10.12 Errors and Exceptions
10.12.1 errorcode Module
10.12.2 errors.Error Exception
10.12.3 errors.DataError Exception
10.12.4 errors.DatabaseError Exception
10.12.5 errors.IntegrityError Exception
10.12.6 errors.InterfaceError Exception
10.12.7 errors.InternalError Exception
10.12.8 errors.NotSupportedError Exception
10.12.9 errors.OperationalError Exception
10.12.10 errors.PoolError Exception
10.12.11 errors.ProgrammingError Exception
10.12.12 errors.Warning Exception
10.12.13 errors.custom_error_exception() Function

This chapter contains the public API reference for Connector/Python. Examples should be considered working for Python 2.7, and Python 3.1 and greater. They might also work for older versions (such as Python 2.4) unless they use features introduced in newer Python versions. For example, exception handling using the as keyword was introduced in Python 2.6 and will not work in Python 2.4.

The following overview shows the mysql.connector package with its modules. Currently, only the most useful modules, classes, and methods for end users are documented.

mysql.connector
  errorcode
  errors
  connection
  constants
  conversion
  cursor
  dbapi
  locales
    eng
      client_error
  protocol
  utils

10.1 mysql.connector Module

The mysql.connector module provides top-level methods and properties.

10.1.1 mysql.connector.connect() Method

This method sets up a connection, establishing a session with the MySQL server. If no arguments are given, it uses the already configured or default values. For a complete list of possible arguments, see Section 7.1, “Connector/Python Connection Arguments”.

A connection with the MySQL server can be established using either the mysql.connector.connect() method or the mysql.connector.MySQLConnection() class:

cnx = mysql.connector.connect(user='joe', database='test')
cnx = MySQLConnection(user='joe', database='test')

For descriptions of connection methods and properties, see Section 10.2, “connection.MySQLConnection Class”.

10.1.2 mysql.connector.apilevel Property

This property is a string that indicates the supported DB API level.


>>> mysql.connector.apilevel
'2.0'

10.1.3 mysql.connector.paramstyle Property

This property is a string that indicates the Connector/Python default parameter style.


>>> mysql.connector.paramstyle
'pyformat'

10.1.4 mysql.connector.threadsafety Property

This property is an integer that indicates the supported level of thread safety provided by Connector/Python.


>>> mysql.connector.threadsafety
1

10.1.5 mysql.connector.__version__ Property

This property indicates the Connector/Python version as a string. It is available as of Connector/Python 1.1.0.


>>> mysql.connector.__version__
'1.1.0'

10.1.6 mysql.connector.__version_info__ Property

This property indicates the Connector/Python version as an array of version components. It is available as of Connector/Python 1.1.0.


>>> mysql.connector.__version_info__
(1, 1, 0, 'a', 0)

10.2 connection.MySQLConnection Class

10.2.1 connection.MySQLConnection() Constructor
10.2.2 MySQLConnection.close() Method
10.2.3 MySQLConnection.commit() Method
10.2.4 MySQLConnection.config() Method
10.2.5 MySQLConnection.connect() Method
10.2.6 MySQLConnection.cursor() Method
10.2.7 MySQLConnection.cmd_change_user() Method
10.2.8 MySQLConnection.cmd_debug() Method
10.2.9 MySQLConnection.cmd_init_db() Method
10.2.10 MySQLConnection.cmd_ping() Method
10.2.11 MySQLConnection.cmd_process_info() Method
10.2.12 MySQLConnection.cmd_process_kill() Method
10.2.13 MySQLConnection.cmd_query() Method
10.2.14 MySQLConnection.cmd_query_iter() Method
10.2.15 MySQLConnection.cmd_quit() Method
10.2.16 MySQLConnection.cmd_refresh() Method
10.2.17 MySQLConnection.cmd_reset_connection() Method
10.2.18 MySQLConnection.cmd_shutdown() Method
10.2.19 MySQLConnection.cmd_statistics() Method
10.2.20 MySQLConnection.disconnect() Method
10.2.21 MySQLConnection.get_row() Method
10.2.22 MySQLConnection.get_rows() Method
10.2.23 MySQLConnection.get_server_info() Method
10.2.24 MySQLConnection.get_server_version() Method
10.2.25 MySQLConnection.is_connected() Method
10.2.26 MySQLConnection.isset_client_flag() Method
10.2.27 MySQLConnection.ping() Method
10.2.28 MySQLConnection.reconnect() Method
10.2.29 MySQLConnection.reset_session() Method
10.2.30 MySQLConnection.rollback() Method
10.2.31 MySQLConnection.set_charset_collation() Method
10.2.32 MySQLConnection.set_client_flags() Method
10.2.33 MySQLConnection.shutdown() Method
10.2.34 MySQLConnection.start_transaction() Method
10.2.35 MySQLConnection.autocommit Property
10.2.36 MySQLConnection.can_consume_results Property
10.2.37 MySQLConnection.charset Property
10.2.38 MySQLConnection.collation Property
10.2.39 MySQLConnection.connection_id Property
10.2.40 MySQLConnection.database Property
10.2.41 MySQLConnection.get_warnings Property
10.2.42 MySQLConnection.in_transaction Property
10.2.43 MySQLConnection.raise_on_warnings Property
10.2.44 MySQLConnection.server_host Property
10.2.45 MySQLConnection.server_port Property
10.2.46 MySQLConnection.sql_mode Property
10.2.47 MySQLConnection.time_zone Property
10.2.48 MySQLConnection.unix_socket Property
10.2.49 MySQLConnection.user Property

The MySQLConnection class is used to open and manage a connection to a MySQL server. It also used to send commands and SQL statements and read the results.

10.2.1 connection.MySQLConnection() Constructor

Syntax:

cnx = MySQLConnection(**kwargs)

The MySQLConnection constructor initializes the attributes and when at least one argument is passed, it tries to connect to the MySQL server.

For a complete list of arguments, see Section 7.1, “Connector/Python Connection Arguments”.

10.2.2 MySQLConnection.close() Method

Syntax:

cnx.close()

close() is a synonym for disconnect(). See Section 10.2.20, “MySQLConnection.disconnect() Method”.

For a connection obtained from a connection pool, close() does not actually close it but returns it to the pool and makes it available for subsequent connection requests. See Section 9.1, “Connector/Python Connection Pooling”.

10.2.3 MySQLConnection.commit() Method

This method sends a COMMIT statement to the MySQL server, committing the current transaction. Since by default Connector/Python does not autocommit, it is important to call this method after every transaction that modifies data for tables that use transactional storage engines.


>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)", ('Jane'))
>>> cnx.commit()

To roll back instead and discard modifications, see the rollback() method.

10.2.4 MySQLConnection.config() Method

Syntax:

cnx.config(**kwargs)

Configures a MySQLConnection instance after it has been instantiated. For a complete list of possible arguments, see Section 7.1, “Connector/Python Connection Arguments”.

Arguments:

  • kwargs: Connection arguments.

You could use the config() method to change (for example) the user name, then call reconnect().

Example:

cnx = mysql.connector.connect(user='joe', database='test')
# Connected as 'joe'
cnx.config(user='jane')
cnx.reconnect()
# Now connected as 'jane'

For a connection obtained from a connection pool, config() raises an exception. See Section 9.1, “Connector/Python Connection Pooling”.

10.2.5 MySQLConnection.connect() Method

Syntax:

MySQLConnection.connect(**kwargs)

This method sets up a connection, establishing a session with the MySQL server. If no arguments are given, it uses the already configured or default values. For a complete list of possible arguments, see Section 7.1, “Connector/Python Connection Arguments”.

Arguments:

  • kwargs: Connection arguments.

Example:

cnx = MySQLConnection(user='joe', database='test')

For a connection obtained from a conection pool, the connection object class is PooledMySQLConnection. A pooled connection differs from an unpooled connection as described in Section 9.1, “Connector/Python Connection Pooling”.

10.2.6 MySQLConnection.cursor() Method

Syntax:

cursor = cnx.cursor([arg=value[, arg=value]...])

This method returns a MySQLCursor() object, or a subclass of it depending on the passed arguments. The returned object is a cursor.CursorBase instance. For more information about cursor objects, see Section 10.5, “cursor.MySQLCursor Class”, and Section 10.6, “Subclasses cursor.MySQLCursor”.

Arguments may be passed to the cursor() method to control what type of cursor to create:

  • If buffered is True, the cursor fetches all rows from the server after an operation is executed. This is useful when queries return small result sets. buffered can be used alone, or in combination with the dictionary or named_tuple argument.

    buffered can also be passed to connect() to set the default buffering mode for all cursors created from the connection object. See Section 7.1, “Connector/Python Connection Arguments”.

    For information about the implications of buffering, see Section 10.6.1, “cursor.MySQLCursorBuffered Class”.

  • If raw is True, the cursor skips the conversion from MySQL data types to Python types when fetching rows. A raw cursor is usually used to get better performance or when you want to do the conversion yourself.

    raw can also be passed to connect() to set the default raw mode for all cursors created from the connection object. See Section 7.1, “Connector/Python Connection Arguments”.

  • If dictionary is True, the cursor returns rows as dictionaries. This argument is available as of Connector/Python 2.0.0.

  • If named_tuple is True, the cursor returns rows as named tuples. This argument is available as of Connector/Python 2.0.0.

  • If prepared is True, the cursor is used for executing prepared statements. This argument is available as of Connector/Python 1.1.2.

  • The cursor_class argument can be used to pass a class to use for instantiating a new cursor. It must be a subclass of cursor.CursorBase.

The returned object depends on the combination of the arguments. Examples:

  • If not buffered and not raw: MySQLCursor

  • If buffered and not raw: MySQLCursorBuffered

  • If not buffered and raw: MySQLCursorRaw

  • If buffered and raw: MySQLCursorBufferedRaw

10.2.7 MySQLConnection.cmd_change_user() Method

Changes the user using username and password. It also causes the specified database to become the default (current) database. It is also possible to change the character set using the charset argument.

Syntax:

cnx.cmd_change_user(username='', password='', database='', charset=33)

Returns a dictionary containing the OK packet information.

10.2.8 MySQLConnection.cmd_debug() Method

Instructs the server to write debugging information to the error log. The connected user must have the SUPER privilege.

Returns a dictionary containing the OK packet information.

10.2.9 MySQLConnection.cmd_init_db() Method

Syntax:

cnx.cmd_init_db(db_name)

This method makes specified database the default (current) database. In subsequent queries, this database is the default for table references that include no explicit database qualifier.

Returns a dictionary containing the OK packet information.

10.2.10 MySQLConnection.cmd_ping() Method

Checks whether the connection to the server is working.

This method is not to be used directly. Use ping() or is_connected() instead.

Returns a dictionary containing the OK packet information.

10.2.11 MySQLConnection.cmd_process_info() Method

This method raises the NotSupportedError exception. Instead, use the SHOW PROCESSLIST statement or query the tables found in the database INFORMATION_SCHEMA.

10.2.12 MySQLConnection.cmd_process_kill() Method

Syntax:

cnx.cmd_process_kill(mysql_pid)

Asks the server to kill the thread specified by mysql_pid. Although still available, it is better to use the KILL SQL statement.

Returns a dictionary containing the OK packet information.

The following two lines have the same effect:


>>> cnx.cmd_process_kill(123)
>>> cnx.cmd_query('KILL 123')

10.2.13 MySQLConnection.cmd_query() Method

Syntax:

cnx.cmd_query(statement)

This method sends the given statement to the MySQL server and returns a result. To send multiple statements, use the cmd_query_iter() method instead.

The returned dictionary contains information depending on what kind of query was executed. If the query is a SELECT statement, the result contains information about columns. Other statements return a dictionary containing OK or EOF packet information.

Errors received from the MySQL server are raised as exceptions. An InterfaceError is raised when multiple results are found.

Returns a dictionary.

10.2.14 MySQLConnection.cmd_query_iter() Method

Syntax:

cnx.cmd_query_iter(statement)

Similar to the cmd_query() method, but returns a generator object to iterate through results. Use cmd_query_iter() when sending multiple statements, and separate the statements with semicolons.

The following example shows how to iterate through the results after sending multiple statements:

statement = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cnx.cmd_query_iter(statement):
  if 'columns' in result:
    columns = result['columns']
    rows = cnx.get_rows()
  else:
    # do something useful with INSERT result

Returns a generator object.

10.2.15 MySQLConnection.cmd_quit() Method

This method sends a QUIT command to the MySQL server, closing the current connection. Since there is no response from the MySQL server, the packet that was sent is returned.

10.2.16 MySQLConnection.cmd_refresh() Method

Syntax:

cnx.cmd_refresh(options)

This method flushes tables or caches, or resets replication server information. The connected user must have the RELOAD privilege.

The options argument should be a bitmask value constructed using constants from the constants.RefreshOption class.

For a list of options, see Section 10.11, “constants.RefreshOption Class”.

Example:


>>> from mysql.connector import RefreshOption
>>> refresh = RefreshOption.LOG | RefreshOption.THREADS
>>> cnx.cmd_refresh(refresh)

10.2.17 MySQLConnection.cmd_reset_connection() Method

Syntax:

cnx.cmd_reset_connection()

Resets the connection by sending a COM_RESET_CONNECTION command to the server to clear the session state.

This method permits the session state to be cleared without reauthenticating. For MySQL servers older than 5.7.3 (when COM_RESET_CONNECTION was introduced), the reset_session() method can be used instead. That method resets the session state by reauthenticating, which is more expensive.

This method was added in Connector/Python 1.2.1.

10.2.18 MySQLConnection.cmd_shutdown() Method

Asks the database server to shut down. The connected user must have the SHUTDOWN privilege.

Returns a dictionary containing the OK packet information.

10.2.19 MySQLConnection.cmd_statistics() Method

Returns a dictionary containing information about the MySQL server including uptime in seconds and the number of running threads, questions, reloads, and open tables.

10.2.20 MySQLConnection.disconnect() Method

This method tries to send a QUIT command and close the socket. It raises no exceptions.

MySQLConnection.close() is a synonymous method name and more commonly used.

To shut down the connection without sending a QUIT command first, use shutdown().

10.2.21 MySQLConnection.get_row() Method

This method retrieves the next row of a query result set, returning a tuple.

The tuple returned by get_row() consists of:

  • The row as a tuple containing byte objects, or None when no more rows are available.

  • EOF packet information as a dictionary containing status_flag and warning_count, or None when the row returned is not the last row.

The get_row() method is used by MySQLCursor to fetch rows.

10.2.22 MySQLConnection.get_rows() Method

Syntax:

cnx.get_rows(count=None)

This method retrieves all or remaining rows of a query result set, returning a tuple containing the rows as sequences and the EOF packet information. The count argument can be used to obtain a given number of rows. If count is not specified or is None, all rows are retrieved.

The tuple returned by get_rows() consists of:

  • A list of tuples containing the row data as byte objects, or an empty list when no rows are available.

  • EOF packet information as a dictionary containing status_flag and warning_count.

An InterfaceError is raised when all rows have been retrieved.

MySQLCursor uses the get_rows() method to fetch rows.

Returns a tuple.

10.2.23 MySQLConnection.get_server_info() Method

This method returns the MySQL server information verbatim as a string, for example '5.6.11-log', or None when not connected.

10.2.24 MySQLConnection.get_server_version() Method

This method returns the MySQL server version as a tuple, or None when not connected.

10.2.25 MySQLConnection.is_connected() Method

Reports whether the connection to MySQL Server is available.

This method checks whether the connection to MySQL is available using the ping() method, but unlike ping(), is_connected() returns True when the connection is available, False otherwise.

10.2.26 MySQLConnection.isset_client_flag() Method

Syntax:

cnx.isset_client_flag(flag)

This method returns True if the client flag was set, False otherwise.

10.2.27 MySQLConnection.ping() Method

Syntax:

cnx.ping(attempts=1, delay=0)

Check whether the connection to the MySQL server is still available.

When reconnect is set to True, one or more attempts are made to try to reconnect to the MySQL server using the reconnect() method. Use the delay argument (seconds) if you want to wait between each retry.

When the connection is not available, an InterfaceError is raised. Use the is_connected() method to check the connection without raising an error.

Raises InterfaceError on errors.

10.2.28 MySQLConnection.reconnect() Method

Syntax:

cnx.reconnect(attempts=1, delay=0)

Attempt to reconnect to the MySQL server.

The argument attempts specifies the number of times a reconnect is tried. The delay argument is the number of seconds to wait between each retry.

You might set the number of attempts higher and use a longer delay when you expect the MySQL server to be down for maintenance, or when you expect the network to be temporarily unavailable.

10.2.29 MySQLConnection.reset_session() Method

Syntax:

cnx.reset_session(user_variables = None, session_variables = None)

Resets the connection by reauthenticating to clear the session state. user_variables, if given, is a dictionary of user variable names and values. session_variables, if given, is a dictionary of system variable names and values. The method sets each variable to the given value.

Example:

user_variables = {'var1': '1', 'var2': '10'}
session_variables = {'wait_timeout': 100000, 'sql_mode': 'TRADITIONAL'}
self.cnx.reset_session(user_variables, session_variables)

This method resets the session state by reauthenticating, which is expensive. For MySQL servers 5.7.3 or later, the cmd_reset_connection() method can be used instead. It is more lightweight because it permits the session state to be cleared without reauthenticating.

This method was added in Connector/Python 1.2.1.

10.2.30 MySQLConnection.rollback() Method

This method sends a ROLLBACK statement to the MySQL server, undoing all data changes from the current transaction. By default, Connector/Python does not autocommit, so it is possible to cancel transactions when using transactional storage engines such as InnoDB.


>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)", ('Jane'))
>>> cnx.rollback()

To commit modifications, see the commit() method.

10.2.31 MySQLConnection.set_charset_collation() Method

Syntax:

cnx.set_charset_collation(charset=None, collation=None)

This method sets the character set and collation to be used for the current connection. The charset argument can be either the name of a character set, or the numerical equivalent as defined in constants.CharacterSet.

When collation is None, the default collation for the character set is used.

In the following example, we set the character set to latin1 and the collation to latin1_swedish_ci (the default collation for: latin1):


>>> cnx = mysql.connector.connect(user='scott')
>>> cnx.set_charset_collation('latin1')

Specify a given collation as follows:


>>> cnx = mysql.connector.connect(user='scott')
>>> cnx.set_charset_collation('latin1', 'latin1_general_ci')

10.2.32 MySQLConnection.set_client_flags() Method

Syntax:

cnx.set_client_flags(flags)

This method sets the client flags to use when connecting to the MySQL server, and returns the new value as an integer. The flags argument can be either an integer or a sequence of valid client flag values (see Section 10.7, “constants.ClientFlag Class”).

If flags is a sequence, each item in the sequence sets the flag when the value is positive or unsets it when negative. For example, to unset LONG_FLAG and set the FOUND_ROWS flags:


>>> from mysql.connector.constants import ClientFlag
>>> cnx.set_client_flags([ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG])
>>> cnx.reconnect()

Note

Client flags are only set or used when connecting to the MySQL server. It is therefore necessary to reconnect after making changes.

10.2.33 MySQLConnection.shutdown() Method

This method closes the socket. It raises no exceptions.

Unlike disconnect(), shutdown() closes the client connection without attempting to send a QUIT command to the server first. Thus, it will not block if the connection is disrupted for some reason such as network failure.

shutdown() was added in Connector/Python 2.0.1.

10.2.34 MySQLConnection.start_transaction() Method

This method starts a transaction. It accepts arguments indicating whether to use a consistent snapshot, which transaction isolation level to use, and the transaction access mode:

cnx.start_transaction(consistent_snapshot=bool,
                      isolation_level=level,
                      readonly=access_mode)

The default consistent_snapshot value is False. If the value is True, Connector/Python sends WITH CONSISTENT SNAPSHOT with the statement. MySQL ignores this for isolation levels for which that option does not apply.

The default isolation_level value is None, and permitted values are 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ', and 'SERIALIZABLE'. If the isolation_level value is None, no isolation level is sent, so the default level applies.

The readonly argument can be True to start the transaction in READ ONLY mode or False to start it in READ WRITE mode. If readonly is omitted, the server's default access mode is used. For details about transaction access mode, see the description for the START TRANSACTION statement at START TRANSACTION, COMMIT, and ROLLBACK Syntax. If the server is older than MySQL 5.6.5, it does not support setting the access mode and Connector/Python raises a ValueError.

Invoking start_transaction() raises a ProgrammingError if invoked while a transaction is currently in progress. This differs from executing a START TRANSACTION SQL statement while a transaction is in progress; the statement implicitly commits the current transaction.

To determine whether a transaction is active for the connection, use the in_transaction property.

start_transaction() was added in MySQL Connector/Python 1.1.0. The readonly argument was added in Connector/Python 1.1.5.

10.2.35 MySQLConnection.autocommit Property

This property can be assigned a value of True or False to enable or disable the autocommit feature of MySQL. The property can be invoked to retrieve the current autocommit setting.

Note

Autocommit is disabled by default when connecting through Connector/Python. This can be enabled using the autocommit connection parameter.

When the autocommit is turned off, you must commit transactions when using transactional storage engines such as InnoDB or NDBCluster.


>>> cnx.autocommit
False
>>> cnx.autocommit = True
>>> cnx.autocommit
True

10.2.36 MySQLConnection.can_consume_results Property

This property indicates the value of the consume_results connection parameter that controls whether result sets produced by queries are automatically read and discarded. See Section 7.1, “Connector/Python Connection Arguments”.

This method was added in Connector/Python 2.1.1.

10.2.37 MySQLConnection.charset Property

This property returns a string indicating which character set is used for the connection, whether or not it is connected.

10.2.38 MySQLConnection.collation Property

This property returns a string indicating which collation is used for the connection, whether or not it is connected.

10.2.39 MySQLConnection.connection_id Property

This property returns the integer connection ID (thread ID or session ID) for the current connection or None when not connected.

10.2.40 MySQLConnection.database Property

This property sets the current (default) database by executing a USE statement. The property can also be used to retrieve the current database name.


>>> cnx.database = 'test'
>>> cnx.database = 'mysql'
>>> cnx.database
u'mysql'

Returns a string.

10.2.41 MySQLConnection.get_warnings Property

This property can be assigned a value of True or False to enable or disable whether warnings should be fetched automatically. The default is False (default). The property can be invoked to retrieve the current warnings setting.

Fetching warnings automatically can be useful when debugging queries. Cursors make warnings available through the method MySQLCursor.fetchwarnings().


>>> cnx.get_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
[(1.0,)]
>>> cursor.fetchwarnings()
[(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]

Returns True or False.

10.2.42 MySQLConnection.in_transaction Property

This property returns True or False to indicate whether a transaction is active for the connection. The value is True regardless of whether you start a transaction using the start_transaction() API call or by directly executing a SQL statement such as START TRANSACTION or BEGIN.


>>> cnx.start_transaction()
>>> cnx.in_transaction
True
>>> cnx.commit()
>>> cnx.in_transaction
False

in_transaction was added in MySQL Connector/Python 1.1.0.

10.2.43 MySQLConnection.raise_on_warnings Property

This property can be assigned a value of True or False to enable or disable whether warnings should raise exceptions. The default is False (default). The property can be invoked to retrieve the current exceptions setting.

Setting raise_on_warnings also sets get_warnings because warnings need to be fetched so they can be raised as exceptions.

Note

You might always want to set the SQL mode if you would like to have the MySQL server directly report warnings as errors (see Section 10.2.46, “MySQLConnection.sql_mode Property”). It is also good to use transactional engines so transactions can be rolled back when catching the exception.

Result sets needs to be fetched completely before any exception can be raised. The following example shows the execution of a query that produces a warning:


>>> cnx.raise_on_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
..
mysql.connector.errors.DataError: 1292: Truncated incorrect DOUBLE value: 'a'

Returns True or False.

10.2.44 MySQLConnection.server_host Property

This read-only property returns the host name or IP address used for connecting to the MySQL server.

Returns a string.

10.2.45 MySQLConnection.server_port Property

This read-only property returns the TCP/IP port used for connecting to the MySQL server.

Returns an integer.

10.2.46 MySQLConnection.sql_mode Property

This property is used to retrieve and set the SQL Modes for the current connection. The value should be a list of different modes separated by comma (","), or a sequence of modes, preferably using the constants.SQLMode class.

To unset all modes, pass an empty string or an empty sequence.


>>> cnx.sql_mode = 'TRADITIONAL,NO_ENGINE_SUBSTITUTION'
>>> cnx.sql_mode.split(',')
[u'STRICT_TRANS_TABLES', u'STRICT_ALL_TABLES', u'NO_ZERO_IN_DATE',
u'NO_ZERO_DATE', u'ERROR_FOR_DIVISION_BY_ZERO', u'TRADITIONAL', 
u'NO_AUTO_CREATE_USER', u'NO_ENGINE_SUBSTITUTION']

>>> from mysql.connector.constants import SQLMode
>>> cnx.sql_mode = [ SQLMode.NO_ZERO_DATE, SQLMode.REAL_AS_FLOAT]
>>> cnx.sql_mode

u'REAL_AS_FLOAT,NO_ZERO_DATE'

Returns a string.

10.2.47 MySQLConnection.time_zone Property

This property is used to set or retrieve the time zone session variable for the current connection.


>>> cnx.time_zone = '+00:00'
>>> cursor = cnx.cursor()
>>> cursor.execute('SELECT NOW()') ; cursor.fetchone()
(datetime.datetime(2012, 6, 15, 11, 24, 36),)
>>> cnx.time_zone = '-09:00'
>>> cursor.execute('SELECT NOW()') ; cursor.fetchone()
(datetime.datetime(2012, 6, 15, 2, 24, 44),)
>>> cnx.time_zone
u'-09:00'

Returns a string.

10.2.48 MySQLConnection.unix_socket Property

This read-only property returns the Unix socket file for connecting to the MySQL server.

Returns a string.

10.2.49 MySQLConnection.user Property

This read-only property returns the user name used for connecting to the MySQL server.

Returns a string.

10.3 pooling.MySQLConnectionPool Class

This class provides for the instantiation and management of connection pools.

10.3.1 pooling.MySQLConnectionPool Constructor

Syntax:

MySQLConnectionPool(pool_name=None,
                    pool_size=5,
                    pool_reset_session=True,
                    **kwargs)

This constructor instantiates an object that manages a connection pool.

Arguments:

  • pool_name: The pool name. If this argument is not given, Connector/Python automatically generates the name, composed from whichever of the host, port, user, and database connection arguments are given in kwargs, in that order.

    It is not an error for multiple pools to have the same name. An application that must distinguish pools by their pool_name property should create each pool with a distinct name.

  • pool_size: The pool size. If this argument is not given, the default is 5.

  • pool_reset_session: Whether to reset session variables when the connection is returned to the pool. This argument was added in Connector/Python 1.1.5. Before 1.1.5, session variables are not reset.

  • kwargs: Optional additional connection arguments, as described in Section 7.1, “Connector/Python Connection Arguments”.

Example:

dbconfig = {
  "database": "test",
  "user":     "joe",
}

cnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name = "mypool",
                                                      pool_size = 3,
                                                      **dbconfig)

10.3.2 MySQLConnectionPool.add_connection() Method

Syntax:

cnxpool.add_connection(cnx = None)

This method adds a new or existing MySQLConnection to the pool, or raises a PoolError if the pool is full.

Arguments:

  • cnx: The MySQLConnection object to be added to the pool. If this argument is missing, the pool creates a new connection and adds it.

Example:

cnxpool.add_connection()    # add new connection to pool
cnxpool.add_connection(cnx) # add existing connection to pool

10.3.3 MySQLConnectionPool.get_connection() Method

Syntax:

cnxpool.get_connection()

This method returns a connection from the pool, or raises a PoolError if no connections are available.

Example:

cnx = cnxpool.get_connection()

10.3.4 MySQLConnectionPool.set_config() Method

Syntax:

cnxpool.set_config(**kwargs)

This method sets the configuration parameters for connections in the pool. Connections requested from the pool after the configuration change use the new parameters. Connections obtained before the change remain unaffected, but when they are closed (returned to the pool) are reopened with the new parameters before being returned by the pool for subsequent connection requests.

Arguments:

  • kwargs: Connection arguments.

Example:

dbconfig = {
  "database": "performance_schema",
  "user":     "admin",
  "password": "secret",
}

cnxpool.set_config(**dbconfig)

10.3.5 MySQLConnectionPool.pool_name Property

Syntax:

cnxpool.pool_name

This property returns the connection pool name.

Example:

name = cnxpool.pool_name

10.4 pooling.PooledMySQLConnection Class

This class is used by MySQLConnectionPool to return a pooled connection instance. It is also the class used for connections obtained with calls to the connect() method that name a connection pool (see Section 9.1, “Connector/Python Connection Pooling”).

PooledMySQLConnection pooled connection objects are similar to MySQLConnection unpooled connection objects, with these differences:

  • To release a pooled connection obtained from a connection pool, invoke its close() method, just as for any unpooled connection. However, for a pooled connection, close() does not actually close the connection but returns it to the pool and makes it available for subsequent connection requests.

  • A pooled connection cannot be reconfigured using its config() method. Connection changes must be done through the pool object itself, as described shortly.

  • A pooled connection has a pool_name property that returns the pool name.

10.4.1 pooling.PooledMySQLConnection Constructor

Syntax:

PooledMySQLConnection(cnxpool, cnx)

This constructor takes connection pool and connection arguments and returns a pooled connection. It is used by the MySQLConnectionPool class.

Arguments:

  • cnxpool: A MySQLConnectionPool instance.

  • cnx: A MySQLConnection instance.

Example:

pcnx = mysql.connector.pooling.PooledMySQLConnection(cnxpool, cnx)

10.4.2 PooledMySQLConnection.close() Method

Syntax:

cnx.close()

Returns a pooled connection to its connection pool.

For a pooled connection, close() does not actually close it but returns it to the pool and makes it available for subsequent connection requests.

If the pool configuration parameters are changed, a returned connection is closed and reopened with the new configuration before being returned from the pool again in response to a connection request.

10.4.3 PooledMySQLConnection.config() Method

For pooled connections, the config() method raises a PoolError exception. Configuration for pooled connections should be done using the pool object.

10.4.4 PooledMySQLConnection.pool_name Property

Syntax:

cnx.pool_name

This property returns the name of the connection pool to which the connection belongs.

Example:

cnx = cnxpool.get_connection()
name = cnx.pool_name

10.5 cursor.MySQLCursor Class

The MySQLCursor class instantiates objects that can execute operations such as SQL statements. Cursor objects interact with the MySQL server using a MySQLConnection object.

To create a cursor, use the cursor() method of a connection object:

import mysql.connector

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor()

Several related classes inherit from MySQLCursor. To create a cursor of one of these types, pass the appropriate arguments to cursor():

10.5.1 cursor.MySQLCursor Constructor

In most cases, the MySQLConnection cursor() method is used to instantiate a MySQLCursor object:

import mysql.connector

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor()

It is also possible to instantiate a cursor by passing a MySQLConnection object to MySQLCursor:

import mysql.connector
from mysql.connector.cursor import MySQLCursor

cnx = mysql.connector.connect(database='world')
cursor = MySQLCursor(cnx)

The connection argument is optional. If omitted, the cursor is created but its execute() method raises an exception.

10.5.2 MySQLCursor.callproc() Method

Syntax:

result_args = cursor.callproc(proc_name, args=())

This method calls the stored procedure named by the proc_name argument. The args sequence of parameters must contain one entry for each argument that the procedure expects. callproc() returns a modified copy of the input sequence. Input parameters are left untouched. Output and input/output parameters may be replaced with new values.

Result sets produced by the stored procedure are automatically fetched and stored as MySQLCursorBuffered instances. For more information about using these result sets, see stored_results().

Suppose that a stored procedure takes two parameters, multiplies the values, and returns the product:

CREATE PROCEDURE multiply(IN pFac1 INT, IN pFac2 INT, OUT pProd INT)
BEGIN
  SET pProd := pFac1 * pFac2;
END;

The following example shows how to execute the multiply() procedure:

>>> args = (5, 6, 0) # 0 is to hold value of the OUT parameter pProd
>>> cursor.callproc('multiply', args)
('5', '6', 30L)

Connector/Python 1.2.1 and up permits parameter types to be specified. To do this, specify a parameter as a two-item tuple consisting of the parameter value and type. Suppose that a procedure sp1() has this definition:

CREATE PROCEDURE sp1(IN pStr1 VARCHAR(20), IN pStr2 VARCHAR(20),
                     OUT pConCat VARCHAR(100))
BEGIN
  SET pConCat := CONCAT(pStr1, pStr2);
END;

To execute this procedure from Connector/Python, specifying a type for the OUT parameter, do this:

args = ('ham', 'eggs', (0, 'CHAR'))
result_args = cursor.callproc('sp1', args)
print(result_args[2])

10.5.3 MySQLCursor.close() Method

Syntax:

cursor.close()

Use close() when you are done using a cursor. This method closes the cursor, resets all results, and ensures that the cursor object has no reference to its original connection object.

10.5.4 MySQLCursor.execute() Method

Syntax:

cursor.execute(operation, params=None, multi=False)
iterator = cursor.execute(operation, params=None, multi=True)

This method executes the given database operation (query or command). The parameters found in the tuple or dictionary params are bound to the variables in the operation. Specify variables using %s or %(name)s parameter style (that is, using format or pyformat style). execute() returns an iterator if multi is True.

This example inserts information about a new employee, then selects the data for that person. The statements are executed as separate execute() operations:

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

select_stmt = "SELECT * FROM employees WHERE emp_no = %(emp_no)s"
cursor.execute(select_stmt, { 'emp_no': 2 })

The data values are converted as necessary from Python objects to something MySQL understands. In the preceding example, the datetime.date() instance is converted to '2012-03-23'.

If multi is set to True, execute() is able to execute multiple statements specified in the operation string. It returns an iterator that enables processing the result of each statement. However, using parameters does not work well in this case, and it is usually a good idea to execute each statement on its own.

The following example selects and inserts data in a single execute() operation and displays the result of each statement:

operation = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cursor.execute(operation, multi=True):
  if result.with_rows:
    print("Rows produced by statement '{}':".format(
      result.statement))
    print(result.fetchall())
  else:
    print("Number of rows affected by statement '{}': {}".format(
      result.statement, result.rowcount))

If the connection is configured to fetch warnings, warnings generated by the operation are available through the MySQLCursor.fetchwarnings() method.

10.5.5 MySQLCursor.executemany() Method

Syntax:

cursor.executemany(operation, seq_of_params)

This method prepares a database operation (query or command) and executes it against all parameter sequences or mappings found in the sequence seq_of_params.

In most cases, the executemany() method iterates through the sequence of parameters, each time passing the current parameters to the the execute() method.

An optimization is applied for inserts: The data values given by the parameter sequences are batched using multiple-row syntax. The following example inserts three records:

data = [
  ('Jane', date(2005, 2, 12)),
  ('Joe', date(2006, 5, 23)),
  ('John', date(2010, 10, 3)),
]
stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)

For the preceding example, the INSERT statement sent to MySQL is:

INSERT INTO employees (first_name, hire_date)
VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')

With the executemany() method, it is not possible to specify multiple statements to execute in the operation argument. Doing so raises an InternalError exception. Consider using execute() with multi=True instead.

10.5.6 MySQLCursor.fetchall() Method

Syntax:

rows = cursor.fetchall()

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.

The following example shows how to retrieve the first two rows of a result set, and then retrieve any remaining rows:

>>> cursor.execute("SELECT * FROM employees ORDER BY emp_no")
>>> head_rows = cursor.fetchmany(size=2)
>>> remaining_rows = cursor.fetchall()

You must fetch all rows for the current query before executing new statements using the same connection.

10.5.7 MySQLCursor.fetchmany() Method

Syntax:

rows = cursor.fetchmany(size=1)

This method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are available, it returns an empty list.

The number of rows returned can be specified using the size argument, which defaults to one. Fewer rows are returned if fewer rows are available than specified.

You must fetch all rows for the current query before executing new statements using the same connection.

10.5.8 MySQLCursor.fetchone() Method

Syntax:

row = cursor.fetchone()

This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available. By default, the returned tuple consists of data returned by the MySQL server, converted to Python objects. If the cursor is a raw cursor, no such conversion occurs; see Section 10.6.2, “cursor.MySQLCursorRaw Class”.

The fetchone() method is used by fetchall() and fetchmany(). It is also used when a cursor is used as an iterator.

The following example shows two equivalent ways to process a query result. The first uses fetchone() in a while loop, the second uses the cursor as an iterator:

# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator 
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)

You must fetch all rows for the current query before executing new statements using the same connection.

10.5.9 MySQLCursor.fetchwarnings() Method

Syntax:

tuples = cursor.fetchwarnings()

This method returns a list of tuples containing warnings generated by the previously executed operation. To set whether to fetch warnings, use the connection's get_warnings property.

The following example shows a SELECT statement that generates a warning:

>>> cnx.get_warnings = True
>>> cursor.execute("SELECT 'a'+1")
>>> cursor.fetchall()
[(1.0,)]
>>> cursor.fetchwarnings()
[(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]

When warnings are generated, it is possible to raise errors instead, using the connection's raise_on_warnings property.

10.5.10 MySQLCursor.stored_results() Method

Syntax:

iterator = cursor.stored_results()

This method returns a list iterator object that can be used to process result sets produced by a stored procedure executed using the callproc() method. The result sets remain available until you use the cursor to execute another operation or call another stored procedure.

The following example executes a stored procedure that produces two result sets, then uses stored_results() to retrieve them:

>>> cursor.callproc('myproc')
()
>>> for result in cursor.stored_results():
...     print result.fetchall()
... 
[(1,)]
[(2,)]

10.5.11 MySQLCursor.column_names Property

Syntax:

sequence = cursor.column_names

This read-only property returns the column names of a result set as sequence of Unicode strings.

The following example shows how to create a dictionary from a tuple containing data with keys using column_names:

cursor.execute("SELECT last_name, first_name, hire_date "
               "FROM employees WHERE emp_no = %s", (123,))
row = dict(zip(cursor.column_names, cursor.fetchone()))
print("{last_name}, {first_name}: {hire_date}".format(row))

Alternatively, as of Connector/Python 2.0.0, you can fetch rows as dictionaries directly; see Section 10.6.4, “cursor.MySQLCursorDict Class”.

10.5.12 MySQLCursor.description Property

Syntax:

tuples = cursor.description

This read-only property returns a list of tuples describing the columns in a result set. Each tuple in the list contains values as follows:

(column_name,
 type,
 None,
 None,
 None,
 None,
 null_ok,
 column_flags)

The following example shows how to interpret description tuples:

import mysql.connector
from mysql.connector import FieldType

...

cursor.execute("SELECT emp_no, last_name, hire_date "
               "FROM employees WHERE emp_no = %s", (123,))
for i in range(len(cursor.description)):
  print("Column {}:".format(i+1))
  desc = cursor.description[i]
  print("  column_name = {}".format(desc[0]))
  print("  type = {} ({})".format(desc[1], FieldType.get_info(desc[1])))
  print("  null_ok = {}".format(desc[6]))
  print("  column_flags = {}".format(desc[7]))

The output looks like this:

Column 1:
  column_name = emp_no
  type = 3 (LONG)
  null_ok = 0
  column_flags = 20483
Column 2:
  column_name = last_name
  type = 253 (VAR_STRING)
  null_ok = 0
  column_flags = 4097
Column 3:
  column_name = hire_date
  type = 10 (DATE)
  null_ok = 0
  column_flags = 4225

The column_flags value is an instance of the constants.FieldFlag class. To see how to interpret it, do this:

>>> from mysql.connector import FieldFlag
>>> FieldFlag.desc

10.5.13 MySQLCursor.lastrowid Property

Syntax:

id = cursor.lastrowid

This read-only property returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement or None when there is no such value available. For example, if you perform an INSERT into a table that contains an AUTO_INCREMENT column, lastrowid returns the AUTO_INCREMENT value for the new row. For an example, see Section 5.3, “Inserting Data Using Connector/Python”.

The lastrowid property is like the mysql_insert_id() C API function; see mysql_insert_id().

10.5.14 MySQLCursor.rowcount Property

Syntax:

count = cursor.rowcount

This read-only property returns the number of rows returned for SELECT statements, or the number of rows affected by DML statements such as INSERT or UPDATE. For an example, see Section 10.5.4, “MySQLCursor.execute() Method”.

For nonbuffered cursors, the row count cannot be known before the rows have been fetched. In this case, the number of rows is -1 immediately after query execution and is incremented as rows are fetched.

The rowcount property is like the mysql_affected_rows() C API function; see mysql_affected_rows().

10.5.15 MySQLCursor.statement Property

Syntax:

str = cursor.statement

This read-only property returns the last executed statement as a string. The statement property can be useful for debugging and displaying what was sent to the MySQL server.

The string can contain multiple statements if a multiple-statement string was executed. This occurs for execute() with multi=True. In this case, the statement property contains the entire statement string and the execute() call returns an iterator that can be used to process results from the individual statements. The statement property for this iterator shows statement strings for the individual statements.

10.5.16 MySQLCursor.with_rows Property

Syntax:

boolean = cursor.with_rows

This read-only property returns True or False to indicate whether the most recently executed operation produced rows.

The with_rows property is useful when it is necessary to determine whether a statement produces a result set and you need to fetch rows. The following example retrieves the rows returned by the SELECT statements, but reports only the affected-rows value for the UPDATE statement:

import mysql.connector

cnx = mysql.connector.connect(user='scott', database='test')
cursor = cnx.cursor()
operation = 'SELECT 1; UPDATE t1 SET c1 = 2; SELECT 2'
for result in cursor.execute(operation, multi=True):
  if result.with_rows:
    result.fetchall()
  else:
    print("Number of affected rows: {}".format(result.rowcount))

10.6 Subclasses cursor.MySQLCursor

The cursor classes described in the following sections inherit from the MySQLCursor class, which is described in Section 10.5, “cursor.MySQLCursor Class”.

10.6.1 cursor.MySQLCursorBuffered Class

The MySQLCursorBuffered class inherits from MySQLCursor.

After executing a query, a MySQLCursorBuffered cursor fetches the entire result set from the server and buffers the rows.

For queries executed using a buffered cursor, row-fetching methods such as fetchone() return rows from the set of buffered rows. For nonbuffered cursors, rows are not fetched from the server until a row-fetching method is called. In this case, you must be sure to fetch all rows of the result set before executing any other statements on the same connection, or an InternalError (Unread result found) exception will be raised.

MySQLCursorBuffered can be useful in situations where multiple queries, with small result sets, need to be combined or computed with each other.

To create a buffered cursor, use the buffered argument when calling a connection's cursor() method. Alternatively, to make all cursors created from the connection buffered by default, use the buffered connection argument.

Example:

import mysql.connector

cnx = mysql.connector.connect()

# Only this particular cursor will buffer results
cursor = cnx.cursor(buffered=True)

# All cursors created from cnx2 will be buffered by default
cnx2 = mysql.connector.connect(buffered=True)

For a practical use case, see Section 6.1, “Tutorial: Raise Employee's Salary Using a Buffered Cursor”.

10.6.2 cursor.MySQLCursorRaw Class

The MySQLCursorRaw class inherits from MySQLCursor.

A MySQLCursorRaw cursor skips the conversion from MySQL data types to Python types when fetching rows. A raw cursor is usually used to get better performance or when you want to do the conversion yourself.

To create a raw cursor, use the raw argument when calling a connection's cursor() method. Alternatively, to make all cursors created from the connection raw by default, use the raw connection argument.

Example:

import mysql.connector

cnx = mysql.connector.connect()

# Only this particular cursor will be raw
cursor = cnx.cursor(raw=True)

# All cursors created from cnx2 will be raw by default
cnx2 = mysql.connector.connect(raw=True)

10.6.3 cursor.MySQLCursorBufferedRaw Class

The MySQLCursorBufferedRaw class inherits from MySQLCursor.

A MySQLCursorBufferedRaw cursor is like a MySQLCursorRaw cursor, but is buffered: After executing a query, it fetches the entire result set from the server and buffers the rows. For information about the implications of buffering, see Section 10.6.1, “cursor.MySQLCursorBuffered Class”.

To create a buffered raw cursor, use the raw and buffered arguments when calling a connection's cursor() method. Alternatively, to make all cursors created from the connection raw and buffered by default, use the raw and buffered connection arguments.

Example:

import mysql.connector

cnx = mysql.connector.connect()

# Only this particular cursor will be raw and buffered
cursor = cnx.cursor(raw=True, buffered=True)

# All cursors created from cnx2 will be raw and buffered by default
cnx2 = mysql.connector.connect(raw=True, buffered=True)

10.6.4 cursor.MySQLCursorDict Class

The MySQLCursorDict class inherits from MySQLCursor. This class is available as of Connector/Python 2.0.0.

A MySQLCursorDict cursor returns each row as a dictionary. The keys for each dictionary object are the column names of the MySQL result.

Example:

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe:")
for row in cursor:
    print("* {Name}".format(Name=row['Name']

The preceding code produces output like this:

Countries in Europe:
* Albania
* Andorra
* Austria
* Belgium
* Bulgaria
...

It may be convenient to pass the dictionary to format() as follows:

cursor.execute("SELECT Name, Population FROM country WHERE Continent = 'Europe'")

print("Countries in Europe with population:")
for row in cursor:
    print("* {Name}: {Population}".format(**row))

10.6.5 cursor.MySQLCursorBufferedDict Class

The MySQLCursorBufferedDict class inherits from MySQLCursor. This class is available as of Connector/Python 2.0.0.

A MySQLCursorBufferedDict cursor is like a MySQLCursorDict cursor, but is buffered: After executing a query, it fetches the entire result set from the server and buffers the rows. For information about the implications of buffering, see Section 10.6.1, “cursor.MySQLCursorBuffered Class”.

To get a buffered cursor that returns dictionaries, add the buffered argument when instantiating a new dictionary cursor:

cursor = cnx.cursor(dictionary=True, buffered=True)

10.6.6 cursor.MySQLCursorNamedTuple Class

The MySQLCursorNamedTuple class inherits from MySQLCursor. This class is available as of Connector/Python 2.0.0.

A MySQLCursorNamedTuple cursor returns each row as a named tuple. The attributes for each named-tuple object are the column names of the MySQL result.

Example:

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(named_tuple=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe with population:")
for row in cursor:
    print("* {Name}: {Population}".format(
        Name=row.Name,
        Population=row.Population
    ))

10.6.7 cursor.MySQLCursorBufferedNamedTuple Class

The MySQLCursorBufferedNamedTuple class inherits from MySQLCursor. This class is available as of Connector/Python 2.0.0.

A MySQLCursorBufferedNamedTuple cursor is like a MySQLCursorNamedTuple cursor, but is buffered: After executing a query, it fetches the entire result set from the server and buffers the rows. For information about the implications of buffering, see Section 10.6.1, “cursor.MySQLCursorBuffered Class”.

To get a buffered cursor that returns named tuples, add the buffered argument when instantiating a new named-tuple cursor:

cursor = cnx.cursor(named_tuple=True, buffered=True)

10.6.8 cursor.MySQLCursorPrepared Class

The MySQLCursorPrepared class inherits from MySQLCursor. This class is available as of Connector/Python 1.1.0.

In MySQL, there are two ways to execute a prepared statement:

  • Use the PREPARE and EXECUTE statements.

  • Use the binary client/server protocol to send and receive data. To repeatedly execute the same statement with different data for different executions, this is more efficient than using PREPARE and EXECUTE. For information about the binary protocol, see C API Prepared Statements.

In Connector/Python, there are two ways to create a cursor that enables execution of prepared statements using the binary protocol. In both cases, the cursor() method of the connection object returns a MySQLCursorPrepared object:

  • The simpler syntax uses a prepared=True argument to the cursor() method. This syntax is available as of Connector/Python 1.1.2.

    import mysql.connector
    
    cnx = mysql.connector.connect(database='employees')
    cursor = cnx.cursor(prepared=True)
    
  • Alternatively, create an instance of the MySQLCursorPrepared class using the cursor_class argument to the cursor() method. This syntax is available as of Connector/Python 1.1.0.

    import mysql.connector
    from mysql.connector.cursor import MySQLCursorPrepared
    
    cnx = mysql.connector.connect(database='employees')
    cursor = cnx.cursor(cursor_class=MySQLCursorPrepared)
    

A cursor instantiated from the MySQLCursorPrepared class works like this:

  • The first time you pass a statement to the cursor's execute() method, it prepares the statement. For subsequent invocations of execute(), the preparation phase is skipped if the statement is the same.

  • The execute() method takes an optional second argument containing a list of data values to associate with parameter markers in the statement. If the list argument is present, there must be one value per parameter marker.

Example:

cursor = cnx.cursor(prepared=True)
stmt = "SELECT fullname FROM employees WHERE id = %s" # (1)
cursor.execute(stmt, (5,))                            # (2)
# ... fetch data ...
cursor.execute(stmt, (10,))                           # (3)
# ... fetch data ...
  1. The %s within the statement is a parameter marker. Do not put quote marks around parameter markers.

  2. For the first call to the execute() method, the cursor prepares the statement. If data is given in the same call, it also executes the statement and you should fetch the data.

  3. For subsequent execute() calls that pass the same SQL statement, the cursor skips the preparation phase.

Prepared statements executed with MySQLCursorPrepared can use the format (%s) or qmark (?) parameterization style. This differs from nonprepared statements executed with MySQLCursor, which can use the format or pyformat parameterization style.

To use multiple prepared statements simultaneously, instantiate multiple cursors from the MySQLCursorPrepared class.

10.7 constants.ClientFlag Class

This class provides constants defining MySQL client flags that can be used when the connection is established to configure the session. The ClientFlag class is available when importing mysql.connector.


>>> import mysql.connector
>>> mysql.connector.ClientFlag.FOUND_ROWS
2

See Section 10.2.32, “MySQLConnection.set_client_flags() Method” and the connection argument client_flag.

The ClientFlag class cannot be instantiated.

10.8 constants.FieldType Class

This class provides all supported MySQL field or data types. They can be useful when dealing with raw data or defining your own converters. The field type is stored with every cursor in the description for each column.

The following example shows how to print the name of the data type for each column in a result set.

from __future__ import print_function
import mysql.connector
from mysql.connector import FieldType

cnx = mysql.connector.connect(user='scott', database='test')
cursor = cnx.cursor()

cursor.execute(
  "SELECT DATE(NOW()) AS `c1`, TIME(NOW()) AS `c2`, "
  "NOW() AS `c3`, 'a string' AS `c4`, 42 AS `c5`")
rows = cursor.fetchall()

for desc in cursor.description:
  colname = desc[0]
  coltype = desc[1]
  print("Column {} has type {}".format(
    colname, FieldType.get_info(coltype)))

cursor.close()
cnx.close()

The FieldType class cannot be instantiated.

10.9 constants.SQLMode Class

This class provides all known MySQL Server SQL Modes. It is mostly used when setting the SQL modes at connection time using the connection's sql_mode property. See Section 10.2.46, “MySQLConnection.sql_mode Property”.

The SQLMode class cannot be instantiated.

10.10 constants.CharacterSet Class

This class provides all known MySQL characters sets and their default collations. For examples, see Section 10.2.31, “MySQLConnection.set_charset_collation() Method”.

The CharacterSet class cannot be instantiated.

10.11 constants.RefreshOption Class

This class performs various flush operations.

  • RefreshOption.GRANT

    Refresh the grant tables, like FLUSH PRIVILEGES.

  • RefreshOption.LOG

    Flush the logs, like FLUSH LOGS.

  • RefreshOption.TABLES

    Flush the table cache, like FLUSH TABLES.

  • RefreshOption.HOSTS

    Flush the host cache, like FLUSH HOSTS.

  • RefreshOption.STATUS

    Reset status variables, like FLUSH STATUS.

  • RefreshOption.THREADS

    Flush the thread cache.

  • RefreshOption.SLAVE

    On a slave replication server, reset the master server information and restart the slave, like RESET SLAVE.

  • RefreshOption.MASTER

    On a master replication server, remove the binary log files listed in the binary log index and truncate the index file, like RESET MASTER.

10.12 Errors and Exceptions

The mysql.connector.errors module defines exception classes for errors and warnings raised by MySQL Connector/Python. Most classes defined in this module are available when you import mysql.connector.

The exception classes defined in this module mostly follow the Python Database API Specification v2.0 (PEP 249). For some MySQL client or server errors it is not always clear which exception to raise. It is good to discuss whether an error should be reclassified by opening a bug report.

MySQL Server errors are mapped with Python exception based on their SQLSTATE value (see Server Error Codes and Messages). The following table shows the SQLSTATE classes and the exception Connector/Python raises. It is, however, possible to redefine which exception is raised for each server error. The default exception is DatabaseError.

Table 10.1 Mapping of Server Errors to Python Exceptions

SQLSTATE ClassConnector/Python Exception
02DataError
02DataError
07DatabaseError
08OperationalError
0ANotSupportedError
21DataError
22DataError
23IntegrityError
24ProgrammingError
25ProgrammingError
26ProgrammingError
27ProgrammingError
28ProgrammingError
2AProgrammingError
2BDatabaseError
2CProgrammingError
2DDatabaseError
2EDatabaseError
33DatabaseError
34ProgrammingError
35ProgrammingError
37ProgrammingError
3CProgrammingError
3DProgrammingError
3FProgrammingError
40InternalError
42ProgrammingError
44InternalError
HZOperationalError
XAIntegrityError
0KOperationalError
HYDatabaseError

10.12.1 errorcode Module

This module contains both MySQL server and client error codes defined as module attributes with the error number as value. Using error codes instead of error numbers could make reading the source code a bit easier.


>>> from mysql.connector import errorcode
>>> errorcode.ER_BAD_TABLE_ERROR
1051

See Server Error Codes and Messages and Client Error Codes and Messages.

10.12.2 errors.Error Exception

This exception is the base class for all other exceptions in the errors module. It can be used to catch all errors in a single except statement.

The following example shows how we could catch syntax errors:

import mysql.connector

try:
  cnx = mysql.connector.connect(user='scott', database='employees')
  cursor = cnx.cursor()
  cursor.execute("SELECT * FORM employees")   # Syntax error in query
  cnx.close()
except mysql.connector.Error as err:
  print("Something went wrong: {}".format(err))

Initializing the exception supports a few optional arguments, namely msg, errno, values and sqlstate. All of them are optional and default to None. errors.Error is internally used by Connector/Python to raise MySQL client and server errors and should not be used by your application to raise exceptions.

The following examples show the result when using no arguments or a combination of the arguments:


>>> from mysql.connector.errors import Error
>>> str(Error())
'Unknown error'

>>> str(Error("Oops! There was an error."))
'Oops! There was an error.'

>>> str(Error(errno=2006))
'2006: MySQL server has gone away'

>>> str(Error(errno=2002, values=('/tmp/mysql.sock', 2)))
"2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)"

>>> str(Error(errno=1146, sqlstate='42S02', msg="Table 'test.spam' doesn't exist"))
"1146 (42S02): Table 'test.spam' doesn't exist"

The example which uses error number 1146 is used when Connector/Python receives an error packet from the MySQL Server. The information is parsed and passed to the Error exception as shown.

Each exception subclassing from Error can be initialized using the previously mentioned arguments. Additionally, each instance has the attributes errno, msg and sqlstate which can be used in your code.

The following example shows how to handle errors when dropping a table which does not exist (when the DROP TABLE statement does not include a IF EXISTS clause):

import mysql.connector
from mysql.connector import errorcode

cnx = mysql.connector.connect(user='scott', database='test')
cursor = cnx.cursor()
try:
  cursor.execute("DROP TABLE spam")
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_BAD_TABLE_ERROR:
    print("Creating table spam")
  else:
    raise

Prior to Connector/Python 1.1.1, the original message passed to errors.Error() is not saved in such a way that it could be retrieved. Instead, the Error.msg attribute was formatted with the error number and SQLSTATE value. As of 1.1.1, only the original message is saved in the Error.msg attribute. The formatted value together with the error number and SQLSTATE value can be obtained by printing or getting the string representation of the error object. Example:

try:
  conn = mysql.connector.connect(database = "baddb")
except mysql.connector.Error as e:
  print "Error code:", e.errno        # error number
  print "SQLSTATE value:", e.sqlstate # SQLSTATE value
  print "Error message:", e.msg       # error message
  print "Error:", e                   # errno, sqlstate, msg values
  s = str(e)
  print "Error:", s                   # errno, sqlstate, msg values

errors.Error is a subclass of the Python StandardError.

10.12.3 errors.DataError Exception

This exception is raised when there were problems with the data. Examples are a column set to NULL that cannot be NULL, out-of-range values for a column, division by zero, column count does not match value count, and so on.

errors.DataError is a subclass of errors.DatabaseError.

10.12.4 errors.DatabaseError Exception

This exception is the default for any MySQL error which does not fit the other exceptions.

errors.DatabaseError is a subclass of errors.Error.

10.12.5 errors.IntegrityError Exception

This exception is raised when the relational integrity of the data is affected. For example, a duplicate key was inserted or a foreign key constraint would fail.

The following example shows a duplicate key error raised as IntegrityError:

cursor.execute("CREATE TABLE t1 (id int, PRIMARY KEY (id))")
try:
  cursor.execute("INSERT INTO t1 (id) VALUES (1)")
  cursor.execute("INSERT INTO t1 (id) VALUES (1)")
except mysql.connector.IntegrityError as err:
  print("Error: {}".format(err))

errors.IntegrityError is a subclass of errors.DatabaseError.

10.12.6 errors.InterfaceError Exception

This exception is raised for errors originating from Connector/Python itself, not related to the MySQL server.

errors.InterfaceError is a subclass of errors.Error.

10.12.7 errors.InternalError Exception

This exception is raised when the MySQL server encounters an internal error, for example, when a deadlock occurred.

errors.InternalError is a subclass of errors.DatabaseError.

10.12.8 errors.NotSupportedError Exception

This exception is raised when some feature was used that is not supported by the version of MySQL that returned the error. It is also raised when using functions or statements that are not supported by stored routines.

errors.NotSupportedError is a subclass of errors.DatabaseError.

10.12.9 errors.OperationalError Exception

This exception is raised for errors which are related to MySQL's operations. For example: too many connections; a host name could not be resolved; bad handshake; server is shutting down, communication errors.

errors.OperationalError is a subclass of errors.DatabaseError.

10.12.10 errors.PoolError Exception

This exception is raised for connection pool errors. errors.PoolError is a subclass of errors.Error.

10.12.11 errors.ProgrammingError Exception

This exception is raised on programming errors, for example when you have a syntax error in your SQL or a table was not found.

The following example shows how to handle syntax errors:

try:
  cursor.execute("CREATE DESK t1 (id int, PRIMARY KEY (id))")
except mysql.connector.ProgrammingError as err:
  if err.errno == errorcode.ER_SYNTAX_ERROR:
    print("Check your syntax!")
  else:
    print("Error: {}".format(err))

errors.ProgrammingError is a subclass of errors.DatabaseError.

10.12.12 errors.Warning Exception

This exception is used for reporting important warnings, however, Connector/Python does not use it. It is included to be compliant with the Python Database Specification v2.0 (PEP-249).

Consider using either more strict Server SQL Modes or the raise_on_warnings connection argument to make Connector/Python raise errors when your queries produce warnings.

errors.Warning is a subclass of the Python StandardError.

10.12.13 errors.custom_error_exception() Function

Syntax:

errors.custom_error_exception(error=None, exception=None)

This method defines custom exceptions for MySQL server errors and returns current customizations.

If error is a MySQL Server error number, you must also pass the exception class. The error argument can be a dictionary, in which case the key is the server error number, and value the class of the exception to be raised.

To reset the customizations, supply an empty dictionary.

import mysql.connector
from mysql.connector import errorcode

# Server error 1028 should raise a DatabaseError
mysql.connector.custom_error_exception(1028, mysql.connector.DatabaseError)

# Or using a dictionary:
mysql.connector.custom_error_exception({
  1028: mysql.connector.DatabaseError,
  1029: mysql.connector.OperationalError,
})

# To reset, pass an empty dictionary:
mysql.connector.custom_error_exception({})