8.1 Application Development with the Connector/Python C Extension (original) (raw)
Installations of Connector/Python from version 2.1.1 on support ause_pure argument tomysql.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) isFalseas of MySQL 8 and defaults toTruein earlier versions. If the C extension is not available on the system thenuse_pureisTrue. - 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 passinguse_pure=False(to use C implementation) oruse_pure=True(to use the Python implementation) as an argument tomysql.connector.connect(). - For Connector/Python installations that do not include the C Extension, passing
use_pure=Falsetomysql.connector.connect()raises an exception. - For older Connector/Python installations that know nothing of the C Extension (before version 2.1.1), passing
use_puretomysql.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 yourDYLD_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 adduse_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.