MySQL Connector/Python Developer Guide  /  The Connector/Python C Extension  /  Application Development with the Connector/Python C Extension

8.1 Application Development with the Connector/Python C Extension

Installations of Connector/Python from version 2.1.1 on support a use_pure argument to mysql.connector.connect() that indicates whether to use the pure Python interface to MySQL or the C Extension that uses the MySQL C client library:

  • By default, use_pure (use the pure Python implementation) is False as of MySQL 8 and defaults to True in earlier versions. If the C extension is not available on the system then use_pure is True.

  • On Linux, the C and Python implementations are available as different packages. You can install one or both implementations on the same system. On Windows and macOS, the packages include both implementations.

    For Connector/Python installations that include both implementations, it can optionally be toggled it by passing use_pure=False (to use C implementation) or use_pure=True (to use the Python implementation) as an argument to mysql.connector.connect().

  • For Connector/Python installations that do not include the C Extension, passing use_pure=False to mysql.connector.connect() raises an exception.

  • For older Connector/Python installations that know nothing of the C Extension (before version 2.1.1), passing use_pure to mysql.connector.connect() raises an exception regardless of its value.

Note

On macOS, if your Connector/Python installation includes the C Extension, but Python scripts are unable to use it, try setting your DYLD_LIBRARY_PATH environment variable the directory containing the C client library. For example:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib   (for sh)
setenv DYLD_LIBRARY_PATH /usr/local/mysql/lib   (for tcsh)

If you built the C Extension from source, this directory should be the one containing the C client library against which the extension was built.

If you need to check whether your Connector/Python installation is aware of the C Extension, test the HAVE_CEXT value. There are different approaches for this. Suppose that your usual arguments for mysql.connector.connect() are specified in a dictionary:

config = {
  'user': 'scott',
  'password': 'password',
  'host': '127.0.0.1',
  'database': 'employees',
}

The following example illustrates one way to add use_pure to the connection arguments:

import mysql.connector

if mysql.connector.__version_info__ > (2, 1) and mysql.connector.HAVE_CEXT:
  config['use_pure'] = False

If use_pure=False and the C Extension is not available, then Connector/Python will automatically fall back to the pure Python implementation.