Debian Codegraph @

mysqlx-connector-python/docs/mysql-connector-python.html

raw
1 <html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>MySQL Connector/Python Developer Guide</title><link rel="stylesheet" type="text/css" href="mvl.css"><meta name="generator" content="DocBook XSL Stylesheets V1.79.1"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div lang="en" class="book"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python"></a>MySQL Connector/Python Developer Guide</h1></div><div><div class="abstract"><p class="title"><b>Abstract</b></p><p>
2 This manual describes how to install and configure MySQL Connector/Python, a
3 self-contained Python driver for communicating with MySQL
4 servers, and how to use it to develop database applications.
5 </p><p>
6 The latest MySQL Connector/Python version is recommended for use with MySQL
7 Server version 8.0 and higher.
8 </p><p>
9 For notes detailing the changes in each release of Connector/Python, see
10 <a class="ulink" href="https://dev.mysql.com/doc/relnotes/connector-python/en/" target="_top">MySQL Connector/Python
11 Release Notes</a>.
12 </p><p>
13 For legal information, see the <a class="link" href="#legalnotice" title="Legal Notices">Legal
14 Notices</a>.
15 </p><p>
16 For help with using MySQL, please visit the
17 <a class="ulink" href="http://forums.mysql.com" target="_top">MySQL Forums</a>, where you
18 can discuss your issues with other MySQL users.
19
20 </p><p><b>Licensing information. </b>
21 This product may include third-party software, used under
22 license. If you are using a Commercial release of MySQL Connector/Python, see
23 the
24 <a class="ulink" href="https://downloads.mysql.com/docs/licenses/connector-python-9.6-com-en.pdf" target="_top">MySQL Connector/Python
25 9.6 Commercial License Information User Manual</a> for
26 licensing information, including licensing information
27 relating to third-party software that may be included in this
28 Commercial release. If you are using a Community release of
29 MySQL Connector/Python, see the
30 <a class="ulink" href="https://downloads.mysql.com/docs/licenses/connector-python-9.6-gpl-en.pdf" target="_top">MySQL Connector/Python
31 9.6 Community License Information User Manual</a> for
32 licensing information, including licensing information
33 relating to third-party software that may be included in this
34 Community release.
35 </p><p>
36 Document generated on:
37
38 2026-01-13
39
40
41
42 (revision: 84232)
43 </p></div></div></div><hr></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="preface"><a href="#preface">Preface and Legal Notices</a></span></dt><dt><span class="chapter"><a href="#connector-python-introduction">1 Introduction to MySQL Connector/Python</a></span></dt><dt><span class="chapter"><a href="#connector-python-coding">2 Guidelines for Python Developers</a></span></dt><dt><span class="chapter"><a href="#connector-python-versions">3 Connector/Python Versions</a></span></dt><dt><span class="chapter"><a href="#connector-python-installation">4 Connector/Python Installation</a></span></dt><dd><dl><dt><span class="section"><a href="#quick-installation-guide">4.1 Quick Installation Guide</a></span></dt><dt><span class="section"><a href="#differences-between-binary-and-source-distribution">4.2 Differences Between Binary And Source Distributions</a></span></dt><dt><span class="section"><a href="#connector-python-obtaining">4.3 Obtaining Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-installation-binary">4.4 Installing Connector/Python from a Binary Distribution</a></span></dt><dd><dl><dt><span class="section"><a href="#id1847">4.4.1 Installing Connector/Python with pip</a></span></dt><dt><span class="section"><a href="#installing-from-rpm">4.4.2 Installing by RPMs</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-installation-source">4.5 Installing Connector/Python from a Source Distribution</a></span></dt><dt><span class="section"><a href="#connector-python-verification">4.6 Verifying Your Connector/Python Installation</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-examples">5 Connector/Python Coding Examples</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-example-connecting">5.1 Connecting to MySQL Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-ddl">5.2 Creating Tables Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-cursor-transaction">5.3 Inserting Data Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-cursor-select">5.4 Querying Data Using Connector/Python</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-tutorials">6 Connector/Python Tutorials</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-tutorial-cursorbuffered">6.1 Tutorial: Raise Employee's Salary Using a Buffered Cursor</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-connecting">7 Connector/Python Connection Establishment</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-connectargs">7.1 Connector/Python Connection Arguments</a></span></dt><dt><span class="section"><a href="#connector-python-option-files">7.2 Connector/Python Option-File Support</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-cext">8 The Connector/Python C Extension</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-cext-development">8.1 Application Development with the Connector/Python C Extension</a></span></dt><dt><span class="section"><a href="#connector-python-cext-module">8.2 The _mysql_connector C Extension Module</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-other">9 Connector/Python Other Topics</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-logging">9.1 Connector/Python Logging</a></span></dt><dt><span class="section"><a href="#connector-python-opentelemetry">9.2 Telemetry Support</a></span></dt><dt><span class="section"><a href="#connector-python-multi">9.3 Executing Multiple Statements</a></span></dt><dt><span class="section"><a href="#connector-python-asyncio">9.4 Asynchronous Connectivity</a></span></dt><dt><span class="section"><a href="#connector-python-connection-pooling">9.5 Connector/Python Connection Pooling</a></span></dt><dt><span class="section"><a href="#connector-python-django-backend">9.6 Connector/Python Django Back End</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-reference">10 Connector/Python API Reference</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysql-connector">10.1 mysql.connector Module</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysql-connector-connect">10.1.1 mysql.connector.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-apilevel">10.1.2 mysql.connector.apilevel Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-paramstyle">10.1.3 mysql.connector.paramstyle Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-threadsafety">10.1.4 mysql.connector.threadsafety Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version">10.1.5 mysql.connector.__version__ Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version-info">10.1.6 mysql.connector.__version_info__ Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlconnection">10.2 connection.MySQLConnection Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlconnection-constructor">10.2.1 connection.MySQLConnection() Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-close">10.2.2 MySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-commit">10.2.3 MySQLConnection.commit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-config">10.2.4 MySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connect">10.2.5 MySQLConnection.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cursor">10.2.6 MySQLConnection.cursor() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-change-user">10.2.7 MySQLConnection.cmd_change_user() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-debug">10.2.8 MySQLConnection.cmd_debug() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-init-db">10.2.9 MySQLConnection.cmd_init_db() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-ping">10.2.10 MySQLConnection.cmd_ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-info">10.2.11 MySQLConnection.cmd_process_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-kill">10.2.12 MySQLConnection.cmd_process_kill() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query">10.2.13 MySQLConnection.cmd_query() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query-iter">10.2.14 MySQLConnection.cmd_query_iter() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-quit">10.2.15 MySQLConnection.cmd_quit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-refresh">10.2.16 MySQLConnection.cmd_refresh() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-reset-connection">10.2.17 MySQLConnection.cmd_reset_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-shutdown">10.2.18 MySQLConnection.cmd_shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-statistics">10.2.19 MySQLConnection.cmd_statistics() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-disconnect">10.2.20 MySQLConnection.disconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-row">10.2.21 MySQLConnection.get_row() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-rows">10.2.22 MySQLConnection.get_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-info">10.2.23 MySQLConnection.get_server_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-version">10.2.24 MySQLConnection.get_server_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-is-connected">10.2.25 MySQLConnection.is_connected() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-isset-client-flag">10.2.26 MySQLConnection.isset_client_flag() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-ping">10.2.27 MySQLConnection.ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reconnect">10.2.28 MySQLConnection.reconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reset-session">10.2.29 MySQLConnection.reset_session() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-rollback">10.2.30 MySQLConnection.rollback() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-charset-collation">10.2.31 MySQLConnection.set_charset_collation() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-client-flags">10.2.32 MySQLConnection.set_client_flags() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-shutdown">10.2.33 MySQLConnection.shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-start-transaction">10.2.34 MySQLConnection.start_transaction() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-autocommit">10.2.35 MySQLConnection.autocommit Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unread-results">10.2.36 MySQLConnection.unread_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-can-consume-results">10.2.37 MySQLConnection.can_consume_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-charset">10.2.38 MySQLConnection.charset Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-client-flags">10.2.39 MySQLConnection.client_flags Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-collation">10.2.40 MySQLConnection.collation Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connected">10.2.41 MySQLConnection.connected Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connection-id">10.2.42 MySQLConnection.connection_id Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-converter-class">10.2.43 MySQLConnection.converter-class Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-database">10.2.44 MySQLConnection.database Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-warnings">10.2.45 MySQLConnection.get_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-in-transaction">10.2.46 MySQLConnection.in_transaction Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-raise-on-warnings">10.2.47 MySQLConnection.raise_on_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-host">10.2.48 MySQLConnection.server_host Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-info">10.2.49 MySQLConnection.server_info Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-port">10.2.50 MySQLConnection.server_port Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-version">10.2.51 MySQLConnection.server_version Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-sql-mode">10.2.52 MySQLConnection.sql_mode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-time-zone">10.2.53 MySQLConnection.time_zone Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-use-unicode">10.2.54 MySQLConnection.use_unicode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unix-socket">10.2.55 MySQLConnection.unix_socket Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-user">10.2.56 MySQLConnection.user Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool">10.3 pooling.MySQLConnectionPool Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-constructor">10.3.1 pooling.MySQLConnectionPool Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-add-connection">10.3.2 MySQLConnectionPool.add_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-get-connection">10.3.3 MySQLConnectionPool.get_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-set-config">10.3.4 MySQLConnectionPool.set_config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-pool-name">10.3.5 MySQLConnectionPool.pool_name Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection">10.4 pooling.PooledMySQLConnection Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-constructor">10.4.1 pooling.PooledMySQLConnection Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-close">10.4.2 PooledMySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-config">10.4.3 PooledMySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-pool-name">10.4.4 PooledMySQLConnection.pool_name Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlcursor">10.5 cursor.MySQLCursor Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlcursor-constructor">10.5.1 cursor.MySQLCursor Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-add-attribute">10.5.2 MySQLCursor.add_attribute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-clear-attributes">10.5.3 MySQLCursor.clear_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-get-attributes">10.5.4 MySQLCursor.get_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-callproc">10.5.5 MySQLCursor.callproc() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-close">10.5.6 MySQLCursor.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-execute">10.5.7 MySQLCursor.execute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-executemany">10.5.8 MySQLCursor.executemany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchall">10.5.9 MySQLCursor.fetchall() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchmany">10.5.10 MySQLCursor.fetchmany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchone">10.5.11 MySQLCursor.fetchone() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-nextset">10.5.12 MySQLCursor.nextset() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchsets">10.5.13 MySQLCursor.fetchsets() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchwarnings">10.5.14 MySQLCursor.fetchwarnings() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-stored-results">10.5.15 MySQLCursor.stored_results() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-column-names">10.5.16 MySQLCursor.column_names Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-description">10.5.17 MySQLCursor.description Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-warnings">10.5.18 MySQLCursor.warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-lastrowid">10.5.19 MySQLCursor.lastrowid Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-rowcount">10.5.20 MySQLCursor.rowcount Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-statement">10.5.21 MySQLCursor.statement Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-with-rows">10.5.22 MySQLCursor.with_rows Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-cursor-subclasses">10.6 Subclasses cursor.MySQLCursor</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffered">10.6.1 cursor.MySQLCursorBuffered Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorraw">10.6.2 cursor.MySQLCursorRaw Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursordict">10.6.3 cursor.MySQLCursorDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffereddict">10.6.4 cursor.MySQLCursorBufferedDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorprepared">10.6.5 cursor.MySQLCursorPrepared Class</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-clientflag">10.7 constants.ClientFlag Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-fieldtype">10.8 constants.FieldType Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-sqlmode">10.9 constants.SQLMode Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-characterset">10.10 constants.CharacterSet Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-refreshoption">10.11 constants.RefreshOption Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors">10.12 Errors and Exceptions</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-errorcode">10.12.1 errorcode Module</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-error">10.12.2 errors.Error Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-dataerror">10.12.3 errors.DataError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-databaseerror">10.12.4 errors.DatabaseError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-integrityerror">10.12.5 errors.IntegrityError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-interfaceerror">10.12.6 errors.InterfaceError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-internalerror">10.12.7 errors.InternalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-notsupportederror">10.12.8 errors.NotSupportedError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-operationalerror">10.12.9 errors.OperationalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-poolerror">10.12.10 errors.PoolError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-programmingerror">10.12.11 errors.ProgrammingError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-warning">10.12.12 errors.Warning Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-custom-error-exception">10.12.13 errors.custom_error_exception() Function</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#connector-python-cext-reference">11 Connector/Python C Extension API Reference</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-cext-mysql-connector">11.1 _mysql_connector Module</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-mysql">11.2 _mysql_connector.MySQL() Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-affected-rows">11.3 _mysql_connector.MySQL.affected_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-autocommit">11.4 _mysql_connector.MySQL.autocommit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-buffered">11.5 _mysql_connector.MySQL.buffered() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-change-user">11.6 _mysql_connector.MySQL.change_user() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-character-set-name">11.7 _mysql_connector.MySQL.character_set_name() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-close">11.8 _mysql_connector.MySQL.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-commit">11.9 _mysql_connector.MySQL.commit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-connect">11.10 _mysql_connector.MySQL.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-connected">11.11 _mysql_connector.MySQL.connected() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-consume-result">11.12 _mysql_connector.MySQL.consume_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-convert-to-mysql">11.13 _mysql_connector.MySQL.convert_to_mysql() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-escape-string">11.14 _mysql_connector.MySQL.escape_string() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-fetch-fields">11.15 _mysql_connector.MySQL.fetch_fields() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-fetch-row">11.16 _mysql_connector.MySQL.fetch_row() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-field-count">11.17 _mysql_connector.MySQL.field_count() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-free-result">11.18 _mysql_connector.MySQL.free_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-character-set-info">11.19 _mysql_connector.MySQL.get_character_set_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-client-info">11.20 _mysql_connector.MySQL.get_client_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-client-version">11.21 _mysql_connector.MySQL.get_client_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-host-info">11.22 _mysql_connector.MySQL.get_host_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-proto-info">11.23 _mysql_connector.MySQL.get_proto_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-server-info">11.24 _mysql_connector.MySQL.get_server_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-server-version">11.25 _mysql_connector.MySQL.get_server_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-ssl-cipher">11.26 _mysql_connector.MySQL.get_ssl_cipher() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-hex-string">11.27 _mysql_connector.MySQL.hex_string() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-insert-id">11.28 _mysql_connector.MySQL.insert_id() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-more-results">11.29 _mysql_connector.MySQL.more_results() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-next-result">11.30 _mysql_connector.MySQL.next_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-num-fields">11.31 _mysql_connector.MySQL.num_fields() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-num-rows">11.32 _mysql_connector.MySQL.num_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-ping">11.33 _mysql_connector.MySQL.ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-query">11.34 _mysql_connector.MySQL.query() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-raw">11.35 _mysql_connector.MySQL.raw() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-refresh">11.36 _mysql_connector.MySQL.refresh() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-reset-connection">11.37 _mysql_connector.MySQL.reset_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-rollback">11.38 _mysql_connector.MySQL.rollback() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-select-db">11.39 _mysql_connector.MySQL.select_db() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-set-character-set">11.40 _mysql_connector.MySQL.set_character_set() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-shutdown">11.41 _mysql_connector.MySQL.shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-stat">11.42 _mysql_connector.MySQL.stat() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-thread-id">11.43 _mysql_connector.MySQL.thread_id() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-use-unicode">11.44 _mysql_connector.MySQL.use_unicode() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-warning-count">11.45 _mysql_connector.MySQL.warning_count() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-have-result-set">11.46 _mysql_connector.MySQL.have_result_set Property</a></span></dt></dl></dd><dt><span class="index"><a href="#ix01">Index</a></span></dt></dl></div><div class="preface"><div class="titlepage"><div><div><h1 class="title"><a name="preface"></a>Preface and Legal Notices</h1></div></div></div><p>
44 This manual describes how to install, configure, and develop
45 database applications using MySQL Connector/Python, the Python driver for
46 communicating with MySQL servers.
47 </p><div class="simplesect"><div class="titlepage"><div><div class="simple"><h2 class="title" style="clear: both"><a name="legalnotice"></a>Legal Notices</h2></div></div></div><p>
48 Copyright © 2012, 2026, Oracle and/or its affiliates.
49 </p><p>
50 <span class="strong"><strong>License Restrictions</strong></span>
51 </p><p>
52 This software and related documentation are provided under a license
53 agreement containing restrictions on use and disclosure and are
54 protected by intellectual property laws. Except as expressly
55 permitted in your license agreement or allowed by law, you may not
56 use, copy, reproduce, translate, broadcast, modify, license,
57 transmit, distribute, exhibit, perform, publish, or display any
58 part, in any form, or by any means. Reverse engineering,
59 disassembly, or decompilation of this software, unless required by
60 law for interoperability, is prohibited.
61 </p><p>
62 <span class="strong"><strong>Warranty Disclaimer</strong></span>
63 </p><p>
64 The information contained herein is subject to change without notice
65 and is not warranted to be error-free. If you find any errors,
66 please report them to us in writing.
67 </p><p>
68 <span class="strong"><strong>Restricted Rights Notice</strong></span>
69 </p><p>
70 If this is software, software documentation, data (as defined in the
71 Federal Acquisition Regulation), or related documentation that is
72 delivered to the U.S. Government or anyone licensing it on behalf of
73 the U.S. Government, then the following notice is applicable:
74 </p><p>
75 U.S. GOVERNMENT END USERS: Oracle programs (including any operating
76 system, integrated software, any programs embedded, installed, or
77 activated on delivered hardware, and modifications of such programs)
78 and Oracle computer documentation or other Oracle data delivered to
79 or accessed by U.S. Government end users are "commercial computer
80 software," "commercial computer software documentation," or "limited
81 rights data" pursuant to the applicable Federal Acquisition
82 Regulation and agency-specific supplemental regulations. As such,
83 the use, reproduction, duplication, release, display, disclosure,
84 modification, preparation of derivative works, and/or adaptation of
85 i) Oracle programs (including any operating system, integrated
86 software, any programs embedded, installed, or activated on
87 delivered hardware, and modifications of such programs), ii) Oracle
88 computer documentation and/or iii) other Oracle data, is subject to
89 the rights and limitations specified in the license contained in the
90 applicable contract. The terms governing the U.S. Government's use
91 of Oracle cloud services are defined by the applicable contract for
92 such services. No other rights are granted to the U.S. Government.
93 </p><p>
94 <span class="strong"><strong>Hazardous Applications Notice</strong></span>
95 </p><p>
96 This software or hardware is developed for general use in a variety
97 of information management applications. It is not developed or
98 intended for use in any inherently dangerous applications, including
99 applications that may create a risk of personal injury. If you use
100 this software or hardware in dangerous applications, then you shall
101 be responsible to take all appropriate fail-safe, backup,
102 redundancy, and other measures to ensure its safe use. Oracle
103 Corporation and its affiliates disclaim any liability for any
104 damages caused by use of this software or hardware in dangerous
105 applications.
106 </p><p>
107 <span class="strong"><strong>Trademark Notice</strong></span>
108 </p><p>
109 Oracle, Java, MySQL, and NetSuite are registered trademarks of
110 Oracle and/or its affiliates. Other names may be trademarks of their
111 respective owners.
112 </p><p>
113 Intel and Intel Inside are trademarks or registered trademarks of
114 Intel Corporation. All SPARC trademarks are used under license and
115 are trademarks or registered trademarks of SPARC International, Inc.
116 AMD, Epyc, and the AMD logo are trademarks or registered trademarks
117 of Advanced Micro Devices. UNIX is a registered trademark of The
118 Open Group.
119 </p><p>
120 <span class="strong"><strong>Third-Party Content, Products, and Services Disclaimer</strong></span>
121 </p><p>
122 This software or hardware and documentation may provide access to or
123 information about content, products, and services from third
124 parties. Oracle Corporation and its affiliates are not responsible
125 for and expressly disclaim all warranties of any kind with respect
126 to third-party content, products, and services unless otherwise set
127 forth in an applicable agreement between you and Oracle. Oracle
128 Corporation and its affiliates will not be responsible for any loss,
129 costs, or damages incurred due to your access to or use of
130 third-party content, products, or services, except as set forth in
131 an applicable agreement between you and Oracle.
132 </p><p>
133 <span class="strong"><strong>Use of This Documentation</strong></span>
134 </p><p>
135 This documentation is NOT distributed under a GPL license. Use of
136 this documentation is subject to the following terms:
137 </p><p>
138 You may create a printed copy of this documentation solely for your
139 own personal use. Conversion to other formats is allowed as long as
140 the actual content is not altered or edited in any way. You shall
141 not publish or distribute this documentation in any form or on any
142 media, except if you distribute the documentation in a manner
143 similar to how Oracle disseminates it (that is, electronically for
144 download on a Web site with the software) or on a CD-ROM or similar
145 medium, provided however that the documentation is disseminated
146 together with the software on the same medium. Any other use, such
147 as any dissemination of printed copies or use of this documentation,
148 in whole or in part, in another publication, requires the prior
149 written consent from an authorized representative of Oracle. Oracle
150 and/or its affiliates reserve any and all rights to this
151 documentation not expressly granted above.
152 </p></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h2 class="title" style="clear: both"><a name="id1556"></a>Documentation Accessibility</h2></div></div></div><p>
153 For information about Oracle's commitment to accessibility, visit
154 the Oracle Accessibility Program website at
155
156
157
158 <a class="ulink" href="http://www.oracle.com/pls/topic/lookup?ctx=acc&amp;id=docacc" target="_top">http://www.oracle.com/pls/topic/lookup?ctx=acc&amp;id=docacc</a>.
159 </p></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h2 class="title" style="clear: both"><a name="id1560"></a>Access to Oracle Support for Accessibility</h2></div></div></div><p>
160 Oracle customers that have purchased support have access to
161 electronic support through My Oracle Support. For information, visit
162
163
164
165 <a class="ulink" href="http://www.oracle.com/pls/topic/lookup?ctx=acc&amp;id=info" target="_top">http://www.oracle.com/pls/topic/lookup?ctx=acc&amp;id=info</a>
166 or visit
167 <code class="code"><a class="ulink" href="http://www.oracle.com/pls/topic/lookup?ctx=acc&amp;id=trs" target="_top">http://www.oracle.com/pls/topic/lookup?ctx=acc&amp;id=trs</a></code>
168 if you are hearing impaired.
169 </p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-introduction"></a>Chapter 1 Introduction to MySQL Connector/Python</h1></div></div></div><a class="indexterm" name="id1567"></a><a class="indexterm" name="id1569"></a><a class="indexterm" name="id1571"></a><a class="indexterm" name="id1573"></a><p>
170 MySQL Connector/Python enables Python programs to access MySQL databases, using an
171 API that is compliant with the
172 <a class="ulink" href="http://www.python.org/dev/peps/pep-0249/" target="_top">Python
173 Database API Specification v2.0 (PEP 249)</a>.
174 </p><p>
175 For notes detailing the changes in each release of Connector/Python, see
176 <a class="ulink" href="https://dev.mysql.com/doc/relnotes/connector-python/en/" target="_top">MySQL Connector/Python Release
177 Notes</a>.
178 </p><p>
179 MySQL Connector/Python includes support for:
180 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
181 Almost all features provided by MySQL Server version 8.0 and
182 higher.
183 </p></li><li class="listitem"><p>
184 Connector/Python supports X DevAPI. For X DevAPI specific documentation,
185 see <a class="ulink" href="https://dev.mysql.com/doc/x-devapi-userguide/en/" target="_top">X DevAPI User Guide</a>.
186 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
187 X DevAPI support was separated into its own package
188 (<code class="literal">mysqlx-connector-python</code>) in Connector/Python 8.3.0.
189 For related information, see
190 <a class="xref" href="#connector-python-installation" title="Chapter 4 Connector/Python Installation">Chapter 4, <i>Connector/Python Installation</i></a>.
191 </p></div></li><li class="listitem"><p>
192 Converting parameter values back and forth between Python and
193 MySQL data types, for example Python <code class="literal">datetime</code>
194 and MySQL <code class="literal">DATETIME</code>. You can turn automatic
195 conversion on for convenience, or off for optimal performance.
196 </p></li><li class="listitem"><p>
197 All MySQL extensions to standard SQL syntax.
198 </p></li><li class="listitem"><p>
199 Protocol compression, which enables compressing the data stream
200 between the client and server.
201 </p></li><li class="listitem"><p>
202 Connections using TCP/IP sockets and on Unix using Unix sockets.
203 </p></li><li class="listitem"><p>
204 Secure TCP/IP connections using SSL.
205 </p></li><li class="listitem"><p>
206 Self-contained driver. Connector/Python does not require the MySQL client
207 library or any Python modules outside the standard library.
208 </p></li></ul></div><p>
209 For information about which versions of Python can be used with
210 different versions of MySQL Connector/Python, see
211 <a class="xref" href="#connector-python-versions" title="Chapter 3 Connector/Python Versions">Chapter 3, <i>Connector/Python Versions</i></a>.
212 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
213 Connector/Python does not support the old MySQL Server authentication
214 methods, which means that MySQL versions prior to 4.1 will not
215 work.
216 </p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-coding"></a>Chapter 2 Guidelines for Python Developers</h1></div></div></div><p>
217 The following guidelines cover aspects of developing MySQL
218 applications that might not be immediately obvious to developers
219 coming from a Python background:
220 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
221 For security, do not hardcode the values needed to connect and
222 log into the database in your main script. Python has the
223 convention of a <code class="literal">config.py</code> module, where you
224 can keep such values separate from the rest of your code.
225 </p></li><li class="listitem"><p>
226 Python scripts often build up and tear down large data
227 structures in memory, up to the limits of available RAM. Because
228 MySQL often deals with data sets that are many times larger than
229 available memory, techniques that optimize storage space and
230 disk I/O are especially important. For example, in MySQL tables,
231 you typically use numeric IDs rather than string-based
232 dictionary keys, so that the key values are compact and have a
233 predictable length. This is especially important for columns
234 that make up the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_primary_key" target="_top">primary
235 key</a> for an <code class="literal">InnoDB</code> table, because those
236 column values are duplicated within each
237 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_secondary_index" target="_top">secondary index</a>.
238 </p></li><li class="listitem"><p>
239 Any application that accepts input must expect to handle bad
240 data.
241 </p><p>
242 The bad data might be accidental, such as out-of-range values or
243 misformatted strings. The application can use server-side checks
244 such as <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_unique_constraint" target="_top">unique
245 constraints</a> and
246 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_not_null_constraint" target="_top">NOT NULL
247 constraints</a>, to keep the bad data from ever reaching the
248 database. On the client side, use techniques such as exception
249 handlers to report any problems and take corrective action.
250 </p><p>
251 The bad data might also be deliberate, representing an
252 <span class="quote">“<span class="quote">SQL injection</span>”</span> attack. For example, input values
253 might contain quotation marks, semicolons, <code class="literal">%</code>
254 and <code class="literal">_</code> wildcard characters and other
255 characters significant in SQL statements. Validate input values
256 to make sure they have only the expected characters. Escape any
257 special characters that could change the intended behavior when
258 substituted into an SQL statement. Never concatenate a user
259 input value into an SQL statement without doing validation and
260 escaping first. Even when accepting input generated by some
261 other program, expect that the other program could also have
262 been compromised and be sending you incorrect or malicious data.
263 </p></li><li class="listitem"><p>
264 Because the result sets from SQL queries can be very large, use
265 the appropriate method to retrieve items from the result set as
266 you loop through them.
267 <a class="link" href="#connector-python-api-mysqlcursor-fetchone" title="10.5.11 MySQLCursor.fetchone() Method">fetchone()</a>
268 retrieves a single item, when you know the result set contains a
269 single row.
270 <a class="link" href="#connector-python-api-mysqlcursor-fetchall" title="10.5.9 MySQLCursor.fetchall() Method">fetchall()</a>
271 retrieves all the items, when you know the result set contains a
272 limited number of rows that can fit comfortably into memory.
273 <a class="link" href="#connector-python-api-mysqlcursor-fetchmany" title="10.5.10 MySQLCursor.fetchmany() Method">fetchmany()</a>
274 is the general-purpose method when you cannot predict the size
275 of the result set: you keep calling it and looping through the
276 returned items, until there are no more results to process.
277 </p></li><li class="listitem"><p>
278 Since Python already has convenient modules such as
279 <code class="literal">pickle</code> and <code class="literal">cPickle</code> to read
280 and write data structures on disk, data that you choose to store
281 in MySQL instead is likely to have special characteristics:
282 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
283 <span class="bold"><strong>Too large to all fit in memory at one
284 time.</strong></span> You use
285 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a> statements to query
286 only the precise items you need, and
287 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html" target="_top">aggregate
288 functions</a> to perform calculations across multiple
289 items. You configure the
290 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/innodb-parameters.html#sysvar_innodb_buffer_pool_size" target="_top"><code class="literal">innodb_buffer_pool_size</code></a>
291 option within the MySQL server to dedicate a certain amount
292 of RAM for caching table and index data.
293 </p></li><li class="listitem"><p>
294 <span class="bold"><strong>Too complex to be represented by a
295 single data structure.</strong></span> You divide the data
296 between different SQL tables. You can recombine data from
297 multiple tables by using a
298 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_join" target="_top">join</a> query. You make sure
299 that related data is kept in sync between different tables
300 by setting up <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_foreign_key" target="_top">foreign
301 key</a> relationships.
302 </p></li><li class="listitem"><p>
303 <span class="bold"><strong>Updated frequently, perhaps by
304 multiple users simultaneously.</strong></span> The updates might
305 only affect a small portion of the data, making it wasteful
306 to write the whole structure each time. You use the SQL
307 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a>,
308 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a>, and
309 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/delete.html" target="_top"><code class="literal">DELETE</code></a> statements to update
310 different items concurrently, writing only the changed
311 values to disk. You use <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/innodb-storage-engine.html" target="_top"><code class="literal">InnoDB</code></a>
312 tables and
313 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_transaction" target="_top">transactions</a> to keep
314 write operations from conflicting with each other, and to
315 return consistent query results even as the underlying data
316 is being updated.
317 </p></li></ul></div></li><li class="listitem"><p>
318 Using MySQL best practices for performance can help your
319 application to scale without requiring major rewrites and
320 architectural changes. See <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/optimization.html" target="_top">Optimization</a> for
321 best practices for MySQL performance. It offers guidelines and
322 tips for SQL tuning, database design, and server configuration.
323 </p></li><li class="listitem"><p>
324 You can avoid reinventing the wheel by learning the MySQL SQL
325 statements for common operations: operators to use in queries,
326 techniques for bulk loading data, and so on. Some statements and
327 clauses are extensions to the basic ones defined by the SQL
328 standard. See
329 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-data-manipulation-statements.html" target="_top">Data Manipulation Statements</a>,
330 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-data-definition-statements.html" target="_top">Data Definition Statements</a>, and
331 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top">SELECT Statement</a> for the main classes of statements.
332 </p></li><li class="listitem"><p>
333 Issuing SQL statements from Python typically involves declaring
334 very long, possibly multi-line string literals. Because string
335 literals within the SQL statements could be enclosed by single
336 quotation, double quotation marks, or contain either of those
337 characters, for simplicity you can use Python's triple-quoting
338 mechanism to enclose the entire statement. For example:
339 </p><pre data-lang="python" class="programlisting">'''It doesn't matter if this string contains 'single'
340 or "double" quotes, as long as there aren't 3 in a
341 row.'''
342 </pre><p>
343 You can use either of the <code class="literal">'</code> or
344 <code class="literal">"</code> characters for triple-quoting multi-line
345 string literals.
346 </p></li><li class="listitem"><p>
347 Many of the secrets to a fast, scalable MySQL application
348 involve using the right syntax at the very start of your setup
349 procedure, in the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/create-table.html" target="_top"><code class="literal">CREATE TABLE</code></a>
350 statements. For example, Oracle recommends the
351 <code class="literal">ENGINE=INNODB</code> clause for most tables, and
352 makes <code class="literal">InnoDB</code> the default storage engine in
353 MySQL 5.5 and up. Using <code class="literal">InnoDB</code> tables enables
354 transactional behavior that helps scalability of read-write
355 workloads and offers automatic
356 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_crash_recovery" target="_top">crash recovery</a>.
357 Another recommendation is to declare a numeric
358 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_primary_key" target="_top">primary key</a> for each
359 table, which offers the fastest way to look up values and can
360 act as a pointer to associated values in other tables (a
361 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_foreign_key" target="_top">foreign key</a>). Also
362 within the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/create-table.html" target="_top"><code class="literal">CREATE TABLE</code></a>
363 statement, using the most compact column data types that meet
364 your application requirements helps performance and scalability
365 because that enables the database server to move less data back
366 and forth between memory and disk.
367 </p></li></ul></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-versions"></a>Chapter 3 Connector/Python Versions</h1></div></div></div><p>
368 This section describes both version releases, such as 8.0.34, along
369 with notes specific to the two implementations (C Extension and Pure
370 Python).
371 </p><div class="simplesect"><div class="titlepage"><div><div class="simple"><h2 class="title" style="clear: both"><a name="connector-python-versions-releases"></a>Connector/Python Releases</h2></div></div></div><p>
372 The following table summarizes the available Connector/Python versions. For
373 series that have reached General Availability (GA) status,
374 development releases in the series prior to the GA version are no
375 longer supported.
376 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
377 MySQL Connectors and other MySQL client tools and applications
378 now synchronize the first digit of their version number with the
379 (highest) MySQL server version they support. For example, MySQL Connector/Python
380 8.0.12 would be designed to support all features of MySQL server
381 version 8 (or lower). This change makes it easy and intuitive to
382 decide which client version to use for which server version.
383 </p><p>
384 Connector/Python 8.0.4 is the first release to use the new numbering. It is
385 the successor to Connector/Python 2.2.3.
386 </p></div><div class="table"><a name="connector-python-versions-listing"></a><p class="title"><b>Table 3.1 Connector/Python Version Reference</b></p><div class="table-contents"><table summary="For each Connector/Python version, this table lists the corresponding MySQL Server versions that it works with, the corresponding Python versions that it works with, and its status."><col width="20%"><col width="20%"><col width="20%"><col width="20%"><thead><tr>
387 <th scope="col">Connector/Python Version</th>
388 <th scope="col">MySQL Server Versions</th>
389 <th scope="col">Python Versions</th>
390 <th scope="col">Connector Status</th>
391 </tr></thead><tbody><tr>
392 <th scope="row">9.5.0 and later</th>
393 <td>8.0 and later</td>
394 <td>3.14, 3.13*, 3.12, 3.11, 3.10</td>
395 <td>General Availability</td>
396 </tr><tr>
397 <th scope="row">9.10 - 9.4.0</th>
398 <td>8.0 and later</td>
399 <td>3.13*, 3.12, 3.11, 3.10, 3.9</td>
400 <td>General Availability</td>
401 </tr><tr>
402 <th scope="row">8.4.0 and 9.0.0</th>
403 <td>8.0 and later</td>
404 <td>3.12, 3.11, 3.10, 3.9, 3.8</td>
405 <td>General Availability</td>
406 </tr><tr>
407 <th scope="row">8.1.0 - 8.3.0</th>
408 <td>5.7 and later</td>
409 <td>3.12 (8.2.0+), 3.11, 3.10, 3.9, 3.8</td>
410 <td>General Availability</td>
411 </tr><tr>
412 <th scope="row">8.0</th>
413 <td>8.0, 5.7, 5.6, 5.5</td>
414 <td>3.11, 3.10, 3.9, 3.8, 3.7, (3.6 before 8.0.29), (2.7 and 3.5 before
415 8.0.24)</td>
416 <td>General Availability</td>
417 </tr><tr>
418 <th scope="row">2.2 (continues as 8.0)</th>
419 <td>5.7, 5.6, 5.5</td>
420 <td>3.5, 3.4, 2.7</td>
421 <td>Developer Milestone, No releases</td>
422 </tr><tr>
423 <th scope="row">2.1</th>
424 <td>5.7, 5.6, 5.5</td>
425 <td>3.5, 3.4, 2.7, 2.6</td>
426 <td>General Availability</td>
427 </tr><tr>
428 <th scope="row">2.0</th>
429 <td>5.7, 5.6, 5.5</td>
430 <td>3.5, 3.4, 2.7, 2.6</td>
431 <td>GA, final release on 2016-10-26</td>
432 </tr><tr>
433 <th scope="row">1.2</th>
434 <td>5.7, 5.6, 5.5 (5.1, 5.0, 4.1)</td>
435 <td>3.4, 3.3, 3.2, 3.1, 2.7, 2.6</td>
436 <td>GA, final release on 2014-08-22</td>
437 </tr></tbody></table></div></div><br class="table-break"><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
438 MySQL server and Python versions within parentheses are known to
439 work with Connector/Python, but are not officially supported. Bugs might
440 not get fixed for those versions.
441 </p></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
442 Python 3.13 enables <code class="literal">ssl.VERIFY_X509_STRICT</code>
443 SSL validation by default, which means SSL certificates must now
444 be RFC-5280 compliant when using Python 3.13 and higher.
445 </p></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
446 On macOS x86_64 ARM: Python 3.7 is not supported with the c-ext
447 implementation; note this is a non-default version of Python on
448 macOS.
449 </p></div></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h2 class="title" style="clear: both"><a name="connector-python-versions-implementations"></a>Connector/Python Implementations</h2></div></div></div><p>
450 Connector/Python implements the MySQL client/server protocol two ways:
451 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
452 As pure Python; an implementation written in Python. It
453 depends on the Python Standard Library.
454 </p><p>
455 The X DevAPI variant of the connector requires Python
456 Protobuf. The required version is 5.29.4.
457 </p></li><li class="listitem"><p>
458 As a C Extension that interfaces with the MySQL C client
459 library. This implementation of the protocol is dependent on
460 the client library, but can use the library provided by MySQL
461 Server packages (see <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/c-api-implementations.html" target="_top">MySQL C API Implementations</a>).
462 </p></li></ul></div><p>
463 Neither implementation of the client/server protocol has any
464 third-party dependencies. However, if you need SSL support, verify
465 that your Python installation has been compiled using the
466 <a class="ulink" href="http://www.openssl.org/" target="_top">OpenSSL</a> libraries.
467 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
468 Support for distutils was removed in Connector/Python 8.0.32.
469 </p></div><p>
470 Python terminology regarding distributions:
471 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
472 <span class="bold"><strong>Built Distribution</strong></span>: A package
473 created in the native packaging format intended for a given
474 platform. It contains both sources and platform-independent
475 bytecode. Connector/Python binary distributions are built distributions.
476 </p></li><li class="listitem"><p>
477 <span class="bold"><strong>Source Distribution</strong></span>: A
478 distribution that contains only source files and is generally
479 platform independent.
480 </p></li></ul></div></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-installation"></a>Chapter 4 Connector/Python Installation</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#quick-installation-guide">4.1 Quick Installation Guide</a></span></dt><dt><span class="section"><a href="#differences-between-binary-and-source-distribution">4.2 Differences Between Binary And Source Distributions</a></span></dt><dt><span class="section"><a href="#connector-python-obtaining">4.3 Obtaining Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-installation-binary">4.4 Installing Connector/Python from a Binary Distribution</a></span></dt><dd><dl><dt><span class="section"><a href="#id1847">4.4.1 Installing Connector/Python with pip</a></span></dt><dt><span class="section"><a href="#installing-from-rpm">4.4.2 Installing by RPMs</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-installation-source">4.5 Installing Connector/Python from a Source Distribution</a></span></dt><dt><span class="section"><a href="#connector-python-verification">4.6 Verifying Your Connector/Python Installation</a></span></dt></dl></div><p>
481 Connector/Python runs on any platform where Python is installed. Make sure
482 Python is installed on your platform:
483 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
484 Python comes preinstalled on most Unix and Unix-like systems,
485 such as Linux, macOS, and FreeBSD. If your system does not have
486 Python preinstalled for some reasons, use its software
487 management system to install it.
488 </p></li><li class="listitem"><p>
489 For Microsoft Windows, a Python installer is available at the
490 <a class="ulink" href="http://python.org/download/" target="_top">Python
491 Download website</a> or via the Microsoft Store.
492 </p></li></ul></div><p>
493 Also make sure Python in your system path.
494 </p><p>
495 Connector/Python includes the classic and X DevAPI APIs, which are
496 installed separately. Each can be installed by a binary or source
497 distribution.
498 </p><p>
499 Binaries of Connector/Python are distributed in the
500 <a class="ulink" href="https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/8/html/packaging_and_distributing_software/introduction-to-rpm_packaging-and-distributing-software" target="_top">RPM</a>
501 and the
502 <a class="ulink" href="https://packaging.python.org/en/latest/discussions/package-formats/#what-is-a-wheel" target="_top">wheel</a>
503 package formats. The source code, on the other hand, is distributed
504 as a compressed archive of source files, from which a wheel package
505 can be built.
506 </p><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="quick-installation-guide"></a>4.1 Quick Installation Guide</h2></div></div></div><p>
507 The recommended way to install Connector/Python is by
508 <a class="ulink" href="https://pip.pypa.io/en/stable/" target="_top">pip</a> and wheel
509 packages. If your system does not have <code class="literal">pip</code>, you
510 can install it with your system's software manager, or with a
511 <a class="ulink" href="https://pip.pypa.io/en/latest/installation/" target="_top">standalone
512 pip installer</a>.
513 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
514 You are strongly recommended to use the latest version of
515 <code class="literal">pip</code> to install Connector/Python. Upgrade your
516 <code class="literal">pip</code> version if needed.
517 </p></div><p>
518 Install the Connector/Python interfaces for the classic MySQL
519 protocol and the X Protocol, respectively, with the following
520 commands.
521 </p><pre class="programlisting"># classic API
522 $ pip install mysql-connector-python
523
524 # X DevAPI
525 $ pip install mysqlx-connector-python
526 </pre><p>
527 Refer to the
528 <a class="ulink" href="https://dev.mysql.com/doc/dev/connector-python/installation.html" target="_top">installation
529 tutorial</a> for alternate means to install X DevAPI.
530 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="differences-between-binary-and-source-distribution"></a>4.2 Differences Between Binary And Source Distributions</h2></div></div></div><p>
531 Installing from a
532 <a class="ulink" href="https://packaging.python.org/en/latest/discussions/package-formats/#what-is-a-wheel" target="_top">wheel</a>
533 (<code class="literal">bdist</code> package) is the recommended, except for
534 Enterprise Linux systems, on which the RPM-based installation
535 method may be preferred.
536 </p><p>
537 Wheels can be directly and easily installed without an extra build
538 step. However, a wheel package is often specific to a particular
539 platform and Python version, so there may be cases in which
540 <code class="literal">pip</code> cannot find a suitable wheel package based
541 on your platform or your Python version. When that happens, you
542 can get the
543 <a class="ulink" href="https://packaging.python.org/en/latest/discussions/package-formats/#what-is-a-source-distribution" target="_top">source
544 distribution</a> (<code class="literal">sdist</code>) and produce a
545 wheel package from it for installing Connector/Python.
546 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
547 Creating a wheel package from an <code class="literal">sdist</code> may
548 fail for some older Python version, as the Connector/Python
549 source code is only compatible with a specific subset of Python
550 versions.
551 </p></div><p>
552 In summary, the recommendation is to use a
553 <code class="literal">bdist</code> unless <code class="literal">pip</code> cannot find
554 a suitable wheel package for your setup, or if you need to custom
555 build a wheel package for some special reasons.
556 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-obtaining"></a>4.3 Obtaining Connector/Python</h2></div></div></div><p>
557 Using <span class="command"><strong>pip</strong></span> is the preferred method to obtain,
558 install, and upgrade Connector/Python. For alternatives, see the
559 <a class="ulink" href="https://dev.mysql.com/downloads/connector/python/" target="_top">Connector/Python download
560 site</a>.
561 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
562 The <code class="literal">mysql-connector-python</code> package installs
563 an interface to the classic MySQL protocol. The X DevAPI is
564 available by its own <code class="literal">mysqlx-connector-python</code>
565 package. Prior to Connector/Python 8.3.0,
566 <code class="literal">mysql-connector-python</code> installed interfaces
567 to both the X and classic protocols.
568 </p></div><p>
569 Most Linux installation packages (except RPMs for Enterprise
570 Linux) are no longer available from Oracle since Connector/Python
571 9.0.0. Using <code class="literal">pip</code> to manage Connector/Python on
572 those Linux distributions is recommended.
573 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-installation-binary"></a>4.4 Installing Connector/Python from a Binary Distribution</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#id1847">4.4.1 Installing Connector/Python with pip</a></span></dt><dt><span class="section"><a href="#installing-from-rpm">4.4.2 Installing by RPMs</a></span></dt></dl></div><p>
574 Connector/Python includes the classic and X DevAPI connector APIs,
575 which are installed separately. Each can be installed by a binary
576 distribution.
577 </p><p>
578 Binaries are distributed in the
579 <a class="ulink" href="https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/8/html/packaging_and_distributing_software/introduction-to-rpm_packaging-and-distributing-software" target="_top">RPM</a>
580 and the
581 <a class="ulink" href="https://packaging.python.org/en/latest/discussions/package-formats/#what-is-a-wheel" target="_top">wheel</a>
582 package formats.
583 </p><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="id1847"></a>4.4.1 Installing Connector/Python with pip</h3></div></div></div><p>
584 Installation via <span class="command"><strong>pip</strong></span> is supported on Windows,
585 macOS, and Linux platforms.
586 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
587 For macOS platforms, DMG installer packages were available for
588 Connector/Python 8.0 and earlier.
589 </p></div><p>
590 Use <span class="command"><strong>pip</strong></span> to install and upgrade Connector/Python:
591 </p><pre data-lang="terminal" class="programlisting"># Installation
592 $&gt; pip install mysql-connector-python
593
594 # Upgrade
595 $&gt; pip install mysql-connector-python --upgrade
596
597 # Optionally, install X DevAPI
598 $&gt; pip install mysqlx-connector-python
599
600 # Upgrade X DevAPI
601 $&gt; pip install mysqlx-connector-python --upgrade
602
603 </pre><p>
604 In case the wheel package you want to install is found in your
605 local file system (for example, you produced a wheel package
606 from a source distribution or downloaded it from somewhere), you
607 can install it as follows:
608 </p><pre data-lang="css" class="programlisting"># Installation
609 $ pip install <em class="replaceable"><code>/path/to/wheel/&lt;wheel package name&gt;</code></em>.whl
610 </pre><h4><a name="id1859"></a>Installation of Optional Features</h4><p>
611 Installation from wheels allow you to install optional
612 dependencies to enable certain features with Connector/Python.
613 For example:
614 </p><pre class="programlisting"># 3rd party packages to enable the telemetry functionality are installed
615 $ pip install mysql-connector-python[telemetry]
616 </pre><p>
617 Similarly, for X DevAPI:
618 </p><pre class="programlisting"># 3rd party packages to enable the compression functionality are installed
619 $ pip install mysqlx-connector-python[compression]
620 </pre><p>
621 These installation options are shortcuts to install all the
622 dependencies needed by some particular features (they are only
623 for your convenience, and you can always install the required
624 dependencies for a feature by yourself):
625 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
626 For the classic protocol:
627 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
628 dns-srv
629 </p></li><li class="listitem"><p>
630 gssapi
631 </p></li><li class="listitem"><p>
632 fido2
633 </p></li><li class="listitem"><p>
634 telemetry
635 </p></li></ul></div></li><li class="listitem"><p>
636 For X Protocol:
637 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
638 dns-srv
639 </p></li><li class="listitem"><p>
640 compression
641 </p></li></ul></div></li></ul></div><p>
642 You can specify a multiple of these options in your installation
643 command, for example:
644
645 </p><pre class="programlisting">$ pip install mysql-connector-python[telemetry,dns-srv,<em class="replaceable"><code>...</code></em>]</pre><p>
646
647 Or, if are installing a wheel package from your local file
648 system:
649
650 </p><pre class="programlisting">$ pip install <em class="replaceable"><code>/path/to/wheel/&lt;wheel package name&gt;</code></em>.whl[telemetry,dns-srv,<em class="replaceable"><code>...</code></em>] </pre><p>
651 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="installing-from-rpm"></a>4.4.2 Installing by RPMs</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#using-the-mysql-yum-repository">4.4.2.1 Using the MySQL Yum Repository</a></span></dt><dt><span class="section"><a href="#using-an-rpm-package">4.4.2.2 Using an RPM Package</a></span></dt></dl></div><p>
652 Installation by RPMs is only supported on RedHat Enterprise
653 Linux and Oracle Linux, and is performed using the MySQL Yum
654 Repository or by using RPM packages downloaded directly from
655 Oracle.
656 </p><div class="section"><div class="titlepage"><div><div><h4 class="title"><a name="using-the-mysql-yum-repository"></a>4.4.2.1 Using the MySQL Yum Repository</h4></div></div></div><p>
657 RedHat Enterprise Linux and Oracle Linux platforms can install
658 Connector/Python using the MySQL Yum repository (see
659 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/linux-installation-yum-repo.html#yum-repo-setup" target="_top">Adding
660 the MySQL Yum Repository</a> and
661 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/linux-installation-yum-repo.html#yum-install-components" target="_top">Installing
662 Additional MySQL Products and Components with Yum</a>).
663 </p><h5><a name="id1898"></a>Prerequisites</h5><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
664 <span class="emphasis"><em>For installing X DevAPI only:</em></span>Because
665 the required <code class="literal">python3-protobuf</code> RPM
666 package is not available for Python 3.8 on the RedHat
667 Enterprise Linux and Oracle Linux platforms, it has to be
668 manually installed with, for example, <code class="literal">pip install
669 protobuf</code>. This is required for Connector/Python
670 8.0.29 or later.
671 </p></li><li class="listitem"><p>
672 The <code class="literal">mysql-community-client-plugins</code>
673 package is required for using robust authentication
674 methods like <code class="literal">caching_sha2_password</code>,
675 which is the default authentication method for MySQL 8.0
676 and later. Install it using the Yum repository
677 </p><pre class="programlisting"> $ sudo yum install mysql-community-client-plugins
678 </pre></li></ul></div><h5><a name="id1910"></a>Installation</h5><p>
679 Use the following commands to install Connector/Python:
680 </p><pre class="programlisting">$ sudo yum install mysql-connector-python
681
682 # Optionally, install also X DevAPI
683 $ sudo yum install mysqlx-connector-python
684 </pre></div><div class="section"><div class="titlepage"><div><div><h4 class="title"><a name="using-an-rpm-package"></a>4.4.2.2 Using an RPM Package</h4></div></div></div><p>
685 Connector/Python RPM packages (<code class="literal">.rpm</code> files)
686 are available from the
687 <a class="ulink" href="https://dev.mysql.com/downloads/connector/python/" target="_top">Connector/Python
688 download site</a>.
689 </p><p>
690 You can verify the integrity and authenticity of the RPM
691 packages before installing them. To learn more, see
692 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.4/en/verifying-package-integrity.html" target="_top">Verifying
693 Package Integrity Using MD5 Checksums or GnuPG</a>.
694 </p><h5><a name="id1920"></a>Prerequisites</h5><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
695 <span class="emphasis"><em>For installing X DevAPI only:</em></span>Because
696 the required <code class="literal">python3-protobuf</code> RPM
697 package is not available for Python 3.8 on the RedHat
698 Enterprise Linux and Oracle Linux platforms, it has to be
699 manually installed with, for example, <code class="literal">pip install
700 protobuf</code>. This is required for Connector/Python
701 8.0.29 or later.
702 </p></li><li class="listitem"><p>
703 The <code class="literal">mysql-community-client-plugins</code>
704 package is required for using robust authentication
705 methods like <code class="literal">caching_sha2_password</code>,
706 which is the default authentication method for MySQL 8.0
707 and later.
708 </p><pre class="programlisting"> $ rpm -i mysql-community-client-plugins-<em class="replaceable"><code>ver</code></em>.<em class="replaceable"><code>distro</code></em>.<em class="replaceable"><code>architecture</code></em>.rpm</pre></li></ul></div><h5><a name="id1935"></a>Installation</h5><p>
709 To install Connector/Python using the downloaded RPM packages:
710 </p><pre class="programlisting">$ rpm -i mysql-connector-python-<em class="replaceable"><code>ver</code></em>.<em class="replaceable"><code>distro</code></em>.<em class="replaceable"><code>architecture</code></em>.rpm
711
712 # Optionally, install X DevAPI
713 $ rpm -i mysqlx-connector-python-<em class="replaceable"><code>ver</code></em>.<em class="replaceable"><code>distro</code></em>.<em class="replaceable"><code>architecture</code></em>.rpm
714 </pre></div></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-installation-source"></a>4.5 Installing Connector/Python from a Source Distribution</h2></div></div></div><p>
715 The Connector/Python source distribution is platform independent, and is
716 packaged in the compressed <code class="literal">tar</code> archive format
717 (<code class="filename">.tar.gz</code> file). See
718 <a class="link" href="#connector-python-obtaining" title="4.3 Obtaining Connector/Python">Obtaining
719 Connector/Python</a>) on how to download them.
720 </p><h3><a name="id1950"></a>Prerequisites for Compiling Connector/Python with the C Extension</h3><p>
721 Source distributions include the C Extension that interfaces with
722 the MySQL C client library. <span class="emphasis"><em>You can build the
723 distribution with or without support for this
724 extension.</em></span> To build Connector/Python with support for the C
725 Extension, the following prerequisites must be satisfied:
726 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
727 Compiling tools:
728 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
729 <span class="emphasis"><em>For Linux platforms:</em></span> A C/C++
730 compiler, such as <span class="command"><strong>gcc</strong></span>.
731 </p></li><li class="listitem"><p>
732 <span class="emphasis"><em>For Windows platforms:</em></span> Current
733 version of Visual Studio.
734 </p></li></ul></div></li><li class="listitem"><p>
735 Python development files.
736 </p></li><li class="listitem"><p>
737 <span class="emphasis"><em>For installing the classic interface
738 only:</em></span> MySQL Server binaries (server may be
739 installed or not installed on the system), including
740 development files (to obtain the MySQL Server binaries, visit
741 the
742 <a class="ulink" href="https://dev.mysql.com/downloads/" target="_top">MySQL
743 download site</a>).
744 </p></li><li class="listitem"><p>
745 <span class="emphasis"><em>For installing the X DevAPI interface only:</em></span> Protobuf C++ (version
746 <code class="code">5.29.4</code>). </p></li></ul></div><h3><a name="id1974"></a>Installing Connector/Python from Source Code Using
747 <code class="literal">pip</code></h3><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
748 We recommend leveraging
749 <a class="ulink" href="https://docs.python.org/3/tutorial/venv.html" target="_top">python
750 virtual environments</a> to encapsulate the package
751 installation instead of installing packages directly into the
752 Python system environment.
753 </p></div><p>
754 <span class="bold"><strong>For installing the classic
755 interface:</strong></span>
756 </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
757 Download the latest version of the <code class="literal">sdist</code> of
758 Connector/Python for the classic MySQL protocol, whose name is
759 in the format of
760 <code class="code">mysql_connector_python-x.y.z.tar.gz</code>.
761 </p></li><li class="listitem"><p>
762 <span class="emphasis"><em>Optional: To include the C Extension</em></span>, use
763 these steps to provide the path to the installation directory
764 of MySQL Server (or to the folder where the server binaries
765 are located) with the <code class="literal">MYSQL_CAPI</code> system
766 variable before running the installation step. On Linux
767 platforms:
768 </p><pre class="programlisting"> $ export MYSQL_CAPI=&lt;path to server binaries&gt;
769 </pre><p>
770 On Windows platforms:
771 </p><pre class="programlisting"> &gt; $env:MYSQL_CAPI=&lt;path to server binaries&gt;
772 </pre><p>
773 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
774 It is not required that the server is actually installed
775 on the system; for compiling the C-extension, the presence
776 of libraries are sufficient
777 </p></div><p>
778 </p></li><li class="listitem"><p>
779 Perform the installation using this command:
780 </p><pre class="programlisting"> pip install ./mysql_connector_python-x.y.z.tar.gz</pre><div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Warning</div><p>
781 DO NOT use <code class="literal">mysql-connector-python</code> instead
782 of <code class="literal">./mysql_connector_python-x.y.z.tar.gz</code>,
783 as the former will install the WHEEL package from the PyPI
784 repository, and the latter will install the local WHEEL that
785 is compiled from the source code.
786 </p></div></li></ol></div><p>
787 <span class="bold"><strong>For installing X DevAPI:</strong></span>
788 </p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
789 Download the latest version of the <code class="literal">sdist</code> of
790 Connector/Python for the MySQL X Protocol, whose name is in
791 the format of
792 <code class="code">mysqlx_connector_python-x.y.z.tar.gz</code>.
793 </p></li><li class="listitem"><p>
794 <span class="emphasis"><em>Optional: To include the Protobuf
795 C-Extension,</em></span> use these commands on Linux platforms
796 to provide the paths to the Protobuf folders by the
797 <code class="literal">MYSQLXPB_*</code> system variables before the
798 installation step:
799 </p><pre class="programlisting"> $ export MYSQLXPB_PROTOBUF=<em class="replaceable"><code>&lt;path to protobuf binaries&gt;</code></em>
800 $ export MYSQLXPB_PROTOBUF_INCLUDE_DIR="${MYSQLXPB_PROTOBUF}/include"
801 $ export MYSQLXPB_PROTOBUF_LIB_DIR="${MYSQLXPB_PROTOBUF}/lib"
802 $ export MYSQLXPB_PROTOC="${MYSQLXPB_PROTOBUF}/bin/protoc"
803 </pre><p>
804 Or these commands on Windows platforms:
805 </p><pre class="programlisting"> &gt; $env:PROTOBUF=<em class="replaceable"><code>&lt;path to protobuf binaries&gt;</code></em>
806 &gt; $env:PROTOBUF_INCLUDE_DIR=$env:PROTOBUF+"\include"
807 &gt; $env:PROTOBUF_LIB_DIR=$env:PROTOBUF+"\lib"
808 &gt; $env:PROTOC=$env:PROTOBUF+"\bin\protoc.exe"
809 </pre></li><li class="listitem"><p>
810 Perform the installation using this command:
811 </p><pre class="programlisting"> pip install ./mysqlx_connector_python-x.y.z.tar.gz</pre><div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Warning</div><p>
812 DO NOT use <code class="literal">mysqlx-connector-python</code>
813 instead of
814 <code class="literal">./mysqlx_connector_python-x.y.z.tar.gz</code>,
815 as the former will install the WHEEL package from the PyPI
816 repository, and the latter will install the local WHEEL that
817 is compiled from the source code.
818 </p></div></li></ol></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-verification"></a>4.6 Verifying Your Connector/Python Installation</h2></div></div></div><h3><a name="verify-installation-pip"></a>Verifying Installations by <code class="literal">pip</code></h3><p>
819 To verify that a Connector/Python package has been installed
820 successfully using <code class="literal">pip</code>, use the following
821 command:
822 </p><pre class="programlisting">$ pip install list
823 </pre><p>
824 If you have installed the classic interface, you should see an
825 output similar to the following:
826 </p><pre class="programlisting">Package Version
827 ---------------------------------------- ----------
828 ... ...
829 mysql-connector-python x.y.z
830 ... ...
831 </pre><p>
832 If you have installed X DevAPI, you should see an output similar
833 to the following:
834 </p><pre class="programlisting">Package Version
835 ---------------------------------------- ----------
836 ... ...
837 mysqlx-connector-python x.y.z
838 ...
839 </pre><h3><a name="verify-installation-rpm"></a>Installed from an RPM</h3><p>
840 The default Connector/Python installation location is
841 <code class="filename">/<em class="replaceable"><code>prefix</code></em>/python<em class="replaceable"><code>X.Y</code></em>/site-packages/</code>,
842 where <em class="replaceable"><code>prefix</code></em> is the location where
843 Python is installed and <em class="replaceable"><code>X.Y</code></em> is the
844 Python version.
845 </p><p>
846 The C Extension is installed as
847 <code class="filename">_mysql_connector.so</code> and
848 <code class="filename">_mysqlxpb.so</code> in the
849 <code class="filename">site-packages</code> directory, not in the
850 <code class="filename">mysql/connector</code> and
851 <code class="filename">mysqlx</code> directories for the classic interface
852 and X DevAPI, respectively.
853 </p><h3><a name="verify-installation-c-extension"></a>Verify the C-extension</h3><p>
854 To verify the C-extension of the classic package is available, run
855 this command:
856 </p><pre class="programlisting">$ python -c "import mysql.connector; assert mysql.connector.HAVE_CEXT; print(f'C-ext is {mysql.connector.HAVE_CEXT}')"
857 </pre><p>
858 If no error is returned, the C-extension has been correctly built
859 and installed.
860 </p><p>
861 Similarly, to verify the C-extension of the X DevAPI package is
862 available, run this command and see if it returns any errors:
863 </p><pre class="programlisting">$ python -c "import mysqlx; assert mysqlx.protobuf.HAVE_MYSQLXPB_CEXT; print(f'C-ext is {mysqlx.protobuf.HAVE_MYSQLXPB_CEXT}')"
864 </pre></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-examples"></a>Chapter 5 Connector/Python Coding Examples</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-example-connecting">5.1 Connecting to MySQL Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-ddl">5.2 Creating Tables Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-cursor-transaction">5.3 Inserting Data Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-cursor-select">5.4 Querying Data Using Connector/Python</a></span></dt></dl></div><p>
865 These coding examples illustrate how to develop Python applications
866 and scripts which connect to MySQL Server using MySQL Connector/Python.
867 </p><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-example-connecting"></a>5.1 Connecting to MySQL Using Connector/Python</h2></div></div></div><p>
868 The <code class="literal">connect()</code> constructor creates a connection
869 to the MySQL server and returns a
870 <code class="literal">MySQLConnection</code> object.
871 </p><p>
872 The following example shows how to connect to the MySQL server:
873 </p><pre data-lang="python" class="programlisting">import mysql.connector
874
875 cnx = mysql.connector.connect(user='scott', password='<em class="replaceable"><code>password</code></em>',
876 host='127.0.0.1',
877 database='employees')
878 cnx.close()
879 </pre><p>
880 <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a> describes the
881 permitted connection arguments.
882 </p><p>
883 It is also possible to create connection objects using the
884 <a class="link" href="#connector-python-api-mysqlconnection" title="10.2 connection.MySQLConnection Class">connection.MySQLConnection()</a>
885 class:
886 </p><pre data-lang="python" class="programlisting">from mysql.connector import (connection)
887
888 cnx = connection.MySQLConnection(user='scott', password='<em class="replaceable"><code>password</code></em>',
889 host='127.0.0.1',
890 database='employees')
891 cnx.close()
892 </pre><p>
893 Both forms (either using the <code class="literal">connect()</code>
894 constructor or the class directly) are valid and functionally
895 equal, but using <code class="literal">connect()</code> is preferred and
896 used by most examples in this manual.
897 </p><p>
898 To handle connection errors, use the <code class="literal">try</code>
899 statement and catch all errors using the
900 <a class="link" href="#connector-python-api-errors-error" title="10.12.2 errors.Error Exception">errors.Error</a>
901 exception:
902 </p><pre data-lang="python" class="programlisting">import mysql.connector
903 from mysql.connector import errorcode
904
905 try:
906 cnx = mysql.connector.connect(user='scott',
907 database='employ')
908 except mysql.connector.Error as err:
909 if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
910 print("Something is wrong with your user name or password")
911 elif err.errno == errorcode.ER_BAD_DB_ERROR:
912 print("Database does not exist")
913 else:
914 print(err)
915 else:
916 cnx.close()
917 </pre><p>
918 Defining connection arguments in a dictionary and using the
919 <code class="literal">**</code> operator is another option:
920 </p><pre data-lang="python" class="programlisting">import mysql.connector
921
922 config = {
923 'user': 'scott',
924 'password': '<em class="replaceable"><code>password</code></em>',
925 'host': '127.0.0.1',
926 'database': 'employees',
927 'raise_on_warnings': True
928 }
929
930 cnx = mysql.connector.connect(**config)
931
932 cnx.close()
933 </pre><p>
934 Defining Logger options, a reconnection routine, and defined as a
935 connection method named connect_to_mysql:
936 </p><pre data-lang="python" class="programlisting">
937 import logging
938 import time
939 import mysql.connector
940
941 # Set up logger
942 logger = logging.getLogger(__name__)
943 logger.setLevel(logging.INFO)
944 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
945
946 # Log to console
947 handler = logging.StreamHandler()
948 handler.setFormatter(formatter)
949 logger.addHandler(handler)
950
951 # Also log to a file
952 file_handler = logging.FileHandler("cpy-errors.log")
953 file_handler.setFormatter(formatter)
954 logger.addHandler(file_handler)
955
956 def connect_to_mysql(config, attempts=3, delay=2):
957 attempt = 1
958 # Implement a reconnection routine
959 while attempt &lt; attempts + 1:
960 try:
961 return mysql.connector.connect(**config)
962 except (mysql.connector.Error, IOError) as err:
963 if (attempts is attempt):
964 # Attempts to reconnect failed; returning None
965 logger.info("Failed to connect, exiting without a connection: %s", err)
966 return None
967 logger.info(
968 "Connection failed: %s. Retrying (%d/%d)...",
969 err,
970 attempt,
971 attempts-1,
972 )
973 # progressive reconnect delay
974 time.sleep(delay ** attempt)
975 attempt += 1
976 return None
977
978 </pre><p>
979 Connecting and using the Sakila database using the above routine,
980 assuming it's defined in a file named
981 <code class="filename">myconnection.py</code>:
982 </p><pre data-lang="python" class="programlisting">
983 from myconnection import connect_to_mysql
984
985 config = {
986 "host": "127.0.0.1",
987 "user": "user",
988 "password": "pass",
989 "database": "sakila",
990 }
991
992 cnx = connect_to_mysql(config, attempts=3)
993
994 if cnx and cnx.is_connected():
995
996 with cnx.cursor() as cursor:
997
998 result = cursor.execute("SELECT * FROM actor LIMIT 5")
999
1000 rows = cursor.fetchall()
1001
1002 for rows in rows:
1003
1004 print(rows)
1005
1006 cnx.close()
1007
1008 else:
1009
1010 print("Could not connect")
1011
1012 </pre><h3><a name="id2089"></a>Using the Connector/Python Python or C Extension</h3><p>
1013 Connector/Python offers two implementations: a pure Python interface and a C
1014 extension that uses the MySQL C client library (see
1015 <a class="xref" href="#connector-python-cext" title="Chapter 8 The Connector/Python C Extension">Chapter 8, <i>The Connector/Python C Extension</i></a>). This can be configured
1016 at runtime using the <code class="literal">use_pure</code> connection
1017 argument. It defaults to <code class="literal">False</code> as of MySQL 8,
1018 meaning the C extension is used. If the C extension is not
1019 available on the system then <code class="literal">use_pure</code> defaults
1020 to <code class="literal">True</code>. Setting
1021 <code class="literal">use_pure=False</code> causes the connection to use the
1022 C Extension if your Connector/Python installation includes it, while
1023 <code class="literal">use_pure=True</code> to <code class="literal">False</code> means
1024 the Python implementation is used if available.
1025 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
1026 The <code class="literal">use_pure</code> option and C extension were
1027 added in Connector/Python 2.1.1.
1028 </p></div><p>
1029 The following example shows how to set <code class="literal">use_pure</code>
1030 to False.
1031 </p><pre data-lang="python" class="programlisting">import mysql.connector
1032
1033 cnx = mysql.connector.connect(user='scott', password='<em class="replaceable"><code>password</code></em>',
1034 host='127.0.0.1',
1035 database='employees',
1036 use_pure=False)
1037 cnx.close()
1038 </pre><p>
1039 It is also possible to use the C Extension directly by importing
1040 the <code class="literal">_mysql_connector</code> module rather than the
1041 <code class="literal">mysql.connector</code> module. For more information,
1042 see <a class="xref" href="#connector-python-cext-module" title="8.2 The _mysql_connector C Extension Module">Section 8.2, “The _mysql_connector C Extension Module”</a>.
1043 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-example-ddl"></a>5.2 Creating Tables Using Connector/Python</h2></div></div></div><p>
1044 All <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_ddl" target="_top">DDL</a> (Data Definition Language)
1045 statements are executed using a handle structure known as a
1046 cursor. The following examples show how to create the tables of
1047 the
1048 <a class="ulink" href="http://dev.mysql.com/doc/employee/en/index.html" target="_top">Employee
1049 Sample Database</a>. You need them for the other examples.
1050 </p><p>
1051 In a MySQL server, tables are very long-lived objects, and are
1052 often accessed by multiple applications written in different
1053 languages. You might typically work with tables that are already
1054 set up, rather than creating them within your own application.
1055 Avoid setting up and dropping tables over and over again, as that
1056 is an expensive operation. The exception is
1057 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_temporary_table" target="_top">temporary tables</a>,
1058 which can be created and dropped quickly within an application.
1059 </p><pre data-lang="python" class="programlisting">from __future__ import print_function
1060
1061 import mysql.connector
1062 from mysql.connector import errorcode
1063
1064 DB_NAME = 'employees'
1065
1066 TABLES = {}
1067 TABLES['employees'] = (
1068 "CREATE TABLE `employees` ("
1069 " `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
1070 " `birth_date` date NOT NULL,"
1071 " `first_name` varchar(14) NOT NULL,"
1072 " `last_name` varchar(16) NOT NULL,"
1073 " `gender` enum('M','F') NOT NULL,"
1074 " `hire_date` date NOT NULL,"
1075 " PRIMARY KEY (`emp_no`)"
1076 ") ENGINE=InnoDB")
1077
1078 TABLES['departments'] = (
1079 "CREATE TABLE `departments` ("
1080 " `dept_no` char(4) NOT NULL,"
1081 " `dept_name` varchar(40) NOT NULL,"
1082 " PRIMARY KEY (`dept_no`), UNIQUE KEY `dept_name` (`dept_name`)"
1083 ") ENGINE=InnoDB")
1084
1085 TABLES['salaries'] = (
1086 "CREATE TABLE `salaries` ("
1087 " `emp_no` int(11) NOT NULL,"
1088 " `salary` int(11) NOT NULL,"
1089 " `from_date` date NOT NULL,"
1090 " `to_date` date NOT NULL,"
1091 " PRIMARY KEY (`emp_no`,`from_date`), KEY `emp_no` (`emp_no`),"
1092 " CONSTRAINT `salaries_ibfk_1` FOREIGN KEY (`emp_no`) "
1093 " REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
1094 ") ENGINE=InnoDB")
1095
1096 TABLES['dept_emp'] = (
1097 "CREATE TABLE `dept_emp` ("
1098 " `emp_no` int(11) NOT NULL,"
1099 " `dept_no` char(4) NOT NULL,"
1100 " `from_date` date NOT NULL,"
1101 " `to_date` date NOT NULL,"
1102 " PRIMARY KEY (`emp_no`,`dept_no`), KEY `emp_no` (`emp_no`),"
1103 " KEY `dept_no` (`dept_no`),"
1104 " CONSTRAINT `dept_emp_ibfk_1` FOREIGN KEY (`emp_no`) "
1105 " REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,"
1106 " CONSTRAINT `dept_emp_ibfk_2` FOREIGN KEY (`dept_no`) "
1107 " REFERENCES `departments` (`dept_no`) ON DELETE CASCADE"
1108 ") ENGINE=InnoDB")
1109
1110 TABLES['dept_manager'] = (
1111 " CREATE TABLE `dept_manager` ("
1112 " `emp_no` int(11) NOT NULL,"
1113 " `dept_no` char(4) NOT NULL,"
1114 " `from_date` date NOT NULL,"
1115 " `to_date` date NOT NULL,"
1116 " PRIMARY KEY (`emp_no`,`dept_no`),"
1117 " KEY `emp_no` (`emp_no`),"
1118 " KEY `dept_no` (`dept_no`),"
1119 " CONSTRAINT `dept_manager_ibfk_1` FOREIGN KEY (`emp_no`) "
1120 " REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,"
1121 " CONSTRAINT `dept_manager_ibfk_2` FOREIGN KEY (`dept_no`) "
1122 " REFERENCES `departments` (`dept_no`) ON DELETE CASCADE"
1123 ") ENGINE=InnoDB")
1124
1125 TABLES['titles'] = (
1126 "CREATE TABLE `titles` ("
1127 " `emp_no` int(11) NOT NULL,"
1128 " `title` varchar(50) NOT NULL,"
1129 " `from_date` date NOT NULL,"
1130 " `to_date` date DEFAULT NULL,"
1131 " PRIMARY KEY (`emp_no`,`title`,`from_date`), KEY `emp_no` (`emp_no`),"
1132 " CONSTRAINT `titles_ibfk_1` FOREIGN KEY (`emp_no`)"
1133 " REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
1134 ") ENGINE=InnoDB")
1135 </pre><p>
1136 The preceding code shows how we are storing the
1137 <code class="literal">CREATE</code> statements in a Python dictionary called
1138 <code class="literal">TABLES</code>. We also define the database in a global
1139 variable called <code class="literal">DB_NAME</code>, which enables you to
1140 easily use a different schema.
1141 </p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(user='scott')
1142 cursor = cnx.cursor()
1143 </pre><p>
1144 A single MySQL server can manage multiple
1145 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_database" target="_top">databases</a>. Typically, you
1146 specify the database to switch to when connecting to the MySQL
1147 server. This example does not connect to the database upon
1148 connection, so that it can make sure the database exists, and
1149 create it if not:
1150 </p><pre data-lang="python" class="programlisting">def create_database(cursor):
1151 try:
1152 cursor.execute(
1153 "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
1154 except mysql.connector.Error as err:
1155 print("Failed creating database: {}".format(err))
1156 exit(1)
1157
1158 try:
1159 cursor.execute("USE {}".format(DB_NAME))
1160 except mysql.connector.Error as err:
1161 print("Database {} does not exists.".format(DB_NAME))
1162 if err.errno == errorcode.ER_BAD_DB_ERROR:
1163 create_database(cursor)
1164 print("Database {} created successfully.".format(DB_NAME))
1165 cnx.database = DB_NAME
1166 else:
1167 print(err)
1168 exit(1)
1169 </pre><p>
1170 We first try to change to a particular database using the
1171 <code class="literal">database</code> property of the connection object
1172 <code class="literal">cnx</code>. If there is an error, we examine the error
1173 number to check if the database does not exist. If so, we call the
1174 <code class="literal">create_database</code> function to create it for us.
1175 </p><p>
1176 On any other error, the application exits and displays the error
1177 message.
1178 </p><p>
1179 After we successfully create or change to the target database, we
1180 create the tables by iterating over the items of the
1181 <code class="literal">TABLES</code> dictionary:
1182 </p><pre data-lang="python" class="programlisting">for table_name in TABLES:
1183 table_description = TABLES[table_name]
1184 try:
1185 print("Creating table {}: ".format(table_name), end='')
1186 cursor.execute(table_description)
1187 except mysql.connector.Error as err:
1188 if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
1189 print("already exists.")
1190 else:
1191 print(err.msg)
1192 else:
1193 print("OK")
1194
1195 cursor.close()
1196 cnx.close()
1197 </pre><p>
1198 To handle the error when the table already exists, we notify the
1199 user that it was already there. Other errors are printed, but we
1200 continue creating tables. (The example shows how to handle the
1201 <span class="quote">“<span class="quote">table already exists</span>”</span> condition for illustration
1202 purposes. In a real application, we would typically avoid the
1203 error condition entirely by using the <code class="literal">IF NOT
1204 EXISTS</code> clause of the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/create-table.html" target="_top"><code class="literal">CREATE
1205 TABLE</code></a> statement.)
1206 </p><p>
1207 The output would be something like this:
1208 </p><pre data-lang="none" class="programlisting">Database employees does not exists.
1209 Database employees created successfully.
1210 Creating table employees: OK
1211 Creating table departments: already exists.
1212 Creating table salaries: already exists.
1213 Creating table dept_emp: OK
1214 Creating table dept_manager: OK
1215 Creating table titles: OK
1216 </pre><p>
1217 To populate the employees tables, use the dump files of the
1218 <a class="ulink" href="http://dev.mysql.com/doc/employee/en/index.html" target="_top">Employee
1219 Sample Database</a>. Note that you only need the data dump
1220 files that you will find in an archive named like
1221 <code class="literal">employees_db-dump-files-1.0.5.tar.bz2</code>. After
1222 downloading the dump files, execute the following commands, adding
1223 connection options to the <span class="command"><strong>mysql</strong></span> commands if
1224 necessary:
1225 </p><pre data-lang="terminal" class="programlisting">$&gt; <strong class="userinput"><code>tar xzf employees_db-dump-files-1.0.5.tar.bz2</code></strong>
1226 $&gt; <strong class="userinput"><code>cd employees_db</code></strong>
1227 $&gt; <strong class="userinput"><code>mysql employees &lt; load_employees.dump</code></strong>
1228 $&gt; <strong class="userinput"><code>mysql employees &lt; load_titles.dump</code></strong>
1229 $&gt; <strong class="userinput"><code>mysql employees &lt; load_departments.dump</code></strong>
1230 $&gt; <strong class="userinput"><code>mysql employees &lt; load_salaries.dump</code></strong>
1231 $&gt; <strong class="userinput"><code>mysql employees &lt; load_dept_emp.dump</code></strong>
1232 $&gt; <strong class="userinput"><code>mysql employees &lt; load_dept_manager.dump</code></strong>
1233 </pre></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-example-cursor-transaction"></a>5.3 Inserting Data Using Connector/Python</h2></div></div></div><p>
1234 Inserting or updating data is also done using the handler
1235 structure known as a cursor. When you use a transactional storage
1236 engine such as <code class="literal">InnoDB</code> (the default in MySQL 5.5
1237 and higher), you must <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_commit" target="_top">commit</a>
1238 the data after a sequence of
1239 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a>,
1240 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/delete.html" target="_top"><code class="literal">DELETE</code></a>, and
1241 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a> statements.
1242 </p><p>
1243 This example shows how to insert new data. The second
1244 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a> depends on the value of the
1245 newly created <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_primary_key" target="_top">primary key</a>
1246 of the first. The example also demonstrates how to use extended
1247 formats. The task is to add a new employee starting to work
1248 tomorrow with a salary set to 50000.
1249 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
1250 The following example uses tables created in the example
1251 <a class="xref" href="#connector-python-example-ddl" title="5.2 Creating Tables Using Connector/Python">Section 5.2, “Creating Tables Using Connector/Python”</a>. The
1252 <code class="literal">AUTO_INCREMENT</code> column option for the primary
1253 key of the <code class="literal">employees</code> table is important to
1254 ensure reliable, easily searchable data.
1255 </p></div><pre data-lang="python" class="programlisting">from __future__ import print_function
1256 from datetime import date, datetime, timedelta
1257 import mysql.connector
1258
1259 cnx = mysql.connector.connect(user='scott', database='employees')
1260 cursor = cnx.cursor()
1261
1262 tomorrow = datetime.now().date() + timedelta(days=1)
1263
1264 add_employee = ("INSERT INTO employees "
1265 "(first_name, last_name, hire_date, gender, birth_date) "
1266 "VALUES (%s, %s, %s, %s, %s)")
1267 add_salary = ("INSERT INTO salaries "
1268 "(emp_no, salary, from_date, to_date) "
1269 "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")
1270
1271 data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
1272
1273 # Insert new employee
1274 cursor.execute(add_employee, data_employee)
1275 emp_no = cursor.lastrowid
1276
1277 # Insert salary information
1278 data_salary = {
1279 'emp_no': emp_no,
1280 'salary': 50000,
1281 'from_date': tomorrow,
1282 'to_date': date(9999, 1, 1),
1283 }
1284 cursor.execute(add_salary, data_salary)
1285
1286 # Make sure data is committed to the database
1287 cnx.commit()
1288
1289 cursor.close()
1290 cnx.close()
1291 </pre><p>
1292 We first open a connection to the MySQL server and store the
1293 <a class="link" href="#connector-python-api-mysqlconnection" title="10.2 connection.MySQLConnection Class">connection
1294 object</a> in the variable <code class="literal">cnx</code>. We then
1295 create a new cursor, by default a
1296 <a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">MySQLCursor</a>
1297 object, using the connection's
1298 <a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
1299 method.
1300 </p><p>
1301 We could calculate tomorrow by calling a database function, but
1302 for clarity we do it in Python using the
1303 <code class="literal">datetime</code> module.
1304 </p><p>
1305 Both <code class="literal">INSERT</code> statements are stored in the
1306 variables called <code class="literal">add_employee</code> and
1307 <code class="literal">add_salary</code>. Note that the second
1308 <code class="literal">INSERT</code> statement uses extended Python format
1309 codes.
1310 </p><p>
1311 The information of the new employee is stored in the tuple
1312 <code class="literal">data_employee</code>. The query to insert the new
1313 employee is executed and we retrieve the newly inserted value for
1314 the <code class="literal">emp_no</code> column (an
1315 <code class="literal">AUTO_INCREMENT</code> column) using the
1316 <code class="literal">lastrowid</code> property of the cursor object.
1317 </p><p>
1318 Next, we insert the new salary for the new employee, using the
1319 <code class="literal">emp_no</code> variable in the dictionary holding the
1320 data. This dictionary is passed to the
1321 <code class="literal">execute()</code> method of the cursor object if an
1322 error occurred.
1323 </p><p>
1324 Since by default Connector/Python turns
1325 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_autocommit" target="_top">autocommit</a> off, and MySQL
1326 5.5 and higher uses transactional <code class="literal">InnoDB</code> tables
1327 by default, it is necessary to commit your changes using the
1328 connection's <code class="literal">commit()</code> method. You could also
1329 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_rollback" target="_top">roll back</a> using the
1330 <code class="literal">rollback()</code> method.
1331 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-example-cursor-select"></a>5.4 Querying Data Using Connector/Python</h2></div></div></div><p>
1332 The following example shows how to
1333 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_query" target="_top">query</a> data using a cursor
1334 created using the connection's
1335 <a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
1336 method. The data returned is formatted and printed on the console.
1337 </p><p>
1338 The task is to select all employees hired in the year 1999 and
1339 print their names and hire dates to the console.
1340 </p><pre data-lang="python" class="programlisting">import datetime
1341 import mysql.connector
1342
1343 cnx = mysql.connector.connect(user='scott', database='employees')
1344 cursor = cnx.cursor()
1345
1346 query = ("SELECT first_name, last_name, hire_date FROM employees "
1347 "WHERE hire_date BETWEEN %s AND %s")
1348
1349 hire_start = datetime.date(1999, 1, 1)
1350 hire_end = datetime.date(1999, 12, 31)
1351
1352 cursor.execute(query, (hire_start, hire_end))
1353
1354 for (first_name, last_name, hire_date) in cursor:
1355 print("{}, {} was hired on {:%d %b %Y}".format(
1356 last_name, first_name, hire_date))
1357
1358 cursor.close()
1359 cnx.close()
1360 </pre><p>
1361 We first open a connection to the MySQL server and store the
1362 <a class="link" href="#connector-python-api-mysqlconnection" title="10.2 connection.MySQLConnection Class">connection
1363 object</a> in the variable <code class="literal">cnx</code>. We then
1364 create a new cursor, by default a
1365 <a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">MySQLCursor</a>
1366 object, using the connection's
1367 <a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
1368 method.
1369 </p><p>
1370 In the preceding example, we store the <code class="literal">SELECT</code>
1371 statement in the variable <code class="literal">query</code>. Note that we
1372 are using unquoted <code class="literal">%s</code>-markers where dates
1373 should have been. Connector/Python converts <code class="literal">hire_start</code> and
1374 <code class="literal">hire_end</code> from Python types to a data type that
1375 MySQL understands and adds the required quotes. In this case, it
1376 replaces the first <code class="literal">%s</code> with
1377 <code class="literal">'1999-01-01'</code>, and the second with
1378 <code class="literal">'1999-12-31'</code>.
1379 </p><p>
1380 We then execute the operation stored in the
1381 <code class="literal">query</code> variable using the
1382 <a class="link" href="#connector-python-api-mysqlcursor-execute" title="10.5.7 MySQLCursor.execute() Method"><code class="literal">execute()</code></a>
1383 method. The data used to replace the <code class="literal">%s</code>-markers
1384 in the query is passed as a tuple: <code class="literal">(hire_start,
1385 hire_end)</code>.
1386 </p><p>
1387 After executing the query, the MySQL server is ready to send the
1388 data. The result set could be zero rows, one row, or 100 million
1389 rows. Depending on the expected volume, you can use different
1390 techniques to process this result set. In this example, we use the
1391 <code class="literal">cursor</code> object as an iterator. The first column
1392 in the row is stored in the variable
1393 <code class="literal">first_name</code>, the second in
1394 <code class="literal">last_name</code>, and the third in
1395 <code class="literal">hire_date</code>.
1396 </p><p>
1397 We print the result, formatting the output using Python's built-in
1398 <code class="literal">format()</code> function. Note that
1399 <code class="literal">hire_date</code> was converted automatically by Connector/Python
1400 to a Python <code class="literal">datetime.date</code> object. This means
1401 that we can easily format the date in a more human-readable form.
1402 </p><p>
1403 The output should be something like this:
1404 </p><pre data-lang="none" class="programlisting">..
1405 Wilharm, LiMin was hired on 16 Dec 1999
1406 Wielonsky, Lalit was hired on 16 Dec 1999
1407 Kamble, Dannz was hired on 18 Dec 1999
1408 DuBourdieux, Zhongwei was hired on 19 Dec 1999
1409 Fujisawa, Rosita was hired on 20 Dec 1999
1410 ..
1411 </pre></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-tutorials"></a>Chapter 6 Connector/Python Tutorials</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-tutorial-cursorbuffered">6.1 Tutorial: Raise Employee's Salary Using a Buffered Cursor</a></span></dt></dl></div><p>
1412 These tutorials illustrate how to develop Python applications and
1413 scripts that connect to a MySQL database server using MySQL Connector/Python.
1414 </p><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-tutorial-cursorbuffered"></a>6.1 Tutorial: Raise Employee's Salary Using a Buffered Cursor</h2></div></div></div><p>
1415 The following example script gives a long-overdue 15% raise
1416 effective tomorrow to all employees who joined in the year 2000
1417 and are still with the company.
1418 </p><p>
1419 To iterate through the selected employees, we use buffered
1420 cursors. (A buffered cursor fetches and buffers the rows of a
1421 result set after executing a query; see
1422 <a class="xref" href="#connector-python-api-mysqlcursorbuffered" title="10.6.1 cursor.MySQLCursorBuffered Class">Section 10.6.1, “cursor.MySQLCursorBuffered Class”</a>.) This
1423 way, it is unnecessary to fetch the rows in a new variables.
1424 Instead, the cursor can be used as an iterator.
1425 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
1426 This script is an example; there are other ways of doing this
1427 simple task.
1428 </p></div><pre data-lang="python" class="programlisting">from __future__ import print_function
1429
1430 from decimal import Decimal
1431 from datetime import datetime, date, timedelta
1432
1433 import mysql.connector
1434
1435 # Connect with the MySQL Server
1436 cnx = mysql.connector.connect(user='scott', database='employees')
1437
1438 # Get two buffered cursors
1439 curA = cnx.cursor(buffered=True)
1440 curB = cnx.cursor(buffered=True)
1441
1442 # Query to get employees who joined in a period defined by two dates
1443 query = (
1444 "SELECT s.emp_no, salary, from_date, to_date FROM employees AS e "
1445 "LEFT JOIN salaries AS s USING (emp_no) "
1446 "WHERE to_date = DATE('9999-01-01')"
1447 "AND e.hire_date BETWEEN DATE(%s) AND DATE(%s)")
1448
1449 # UPDATE and INSERT statements for the old and new salary
1450 update_old_salary = (
1451 "UPDATE salaries SET to_date = %s "
1452 "WHERE emp_no = %s AND from_date = %s")
1453 insert_new_salary = (
1454 "INSERT INTO salaries (emp_no, from_date, to_date, salary) "
1455 "VALUES (%s, %s, %s, %s)")
1456
1457 # Select the employees getting a raise
1458 curA.execute(query, (date(2000, 1, 1), date(2000, 12, 31)))
1459
1460 # Iterate through the result of curA
1461 for (emp_no, salary, from_date, to_date) in curA:
1462
1463 # Update the old and insert the new salary
1464 new_salary = int(round(salary * Decimal('1.15')))
1465 curB.execute(update_old_salary, (tomorrow, emp_no, from_date))
1466 curB.execute(insert_new_salary,
1467 (emp_no, tomorrow, date(9999, 1, 1,), new_salary))
1468
1469 # Commit the changes
1470 cnx.commit()
1471
1472 cnx.close()
1473 </pre></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-connecting"></a>Chapter 7 Connector/Python Connection Establishment</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-connectargs">7.1 Connector/Python Connection Arguments</a></span></dt><dt><span class="section"><a href="#connector-python-option-files">7.2 Connector/Python Option-File Support</a></span></dt></dl></div><p>
1474 Connector/Python provides a <code class="literal">connect()</code> call used to establish
1475 connections to the MySQL server. The following sections describe the
1476 permitted arguments for <code class="literal">connect()</code> and describe
1477 how to use option files that supply additional arguments.
1478 </p><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-connectargs"></a>7.1 Connector/Python Connection Arguments</h2></div></div></div><p>
1479 A connection with the MySQL server can be established using either
1480 the <code class="literal">mysql.connector.connect()</code> function or the
1481 <code class="literal">mysql.connector.MySQLConnection()</code> class:
1482 </p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(user='joe', database='test')
1483 cnx = MySQLConnection(user='joe', database='test')
1484 </pre><p>
1485 The following table describes the arguments that can be used to
1486 initiate a connection. An asterisk (*) following an argument
1487 indicates a synonymous argument name, available only for
1488 compatibility with other Python MySQL drivers. Oracle recommends
1489 not to use these alternative names.
1490 </p><div class="table"><a name="connector-python-connectargs-listing"></a><p class="title"><b>Table 7.1 Connection Arguments for Connector/Python</b></p><div class="table-contents"><table><col width="30%"><col width="15%"><col width="55%"><thead><tr>
1491 <th scope="col">Argument Name</th>
1492 <th scope="col">Default</th>
1493 <th scope="col">Description</th>
1494 </tr></thead><tbody><tr>
1495 <th scope="row"><code class="literal">user</code> (<code class="literal">username</code>*)</th>
1496 <td></td>
1497 <td>The user name used to authenticate with the MySQL server.</td>
1498 </tr><tr>
1499 <th scope="row"><code class="literal">password</code> (<code class="literal">passwd</code>*)</th>
1500 <td></td>
1501 <td>The password to authenticate the user with the MySQL server.</td>
1502 </tr><tr>
1503 <th scope="row"><code class="literal">password1</code>, <code class="literal">password2</code>, and
1504 <code class="literal">password3</code></th>
1505 <td></td>
1506 <td>For Multi-Factor Authentication (MFA); <code class="option">password1</code> is an
1507 alias for <code class="option">password</code>. Added in 8.0.28.</td>
1508 </tr><tr>
1509 <th scope="row"><code class="literal">database</code> (<code class="literal">db</code>*)</th>
1510 <td></td>
1511 <td>The database name to use when connecting with the MySQL server.</td>
1512 </tr><tr>
1513 <th scope="row"><code class="literal">host</code></th>
1514 <td>127.0.0.1</td>
1515 <td>The host name or IP address of the MySQL server.</td>
1516 </tr><tr>
1517 <th scope="row"><code class="literal">unix_socket</code></th>
1518 <td></td>
1519 <td>The location of the Unix socket file.</td>
1520 </tr><tr>
1521 <th scope="row"><code class="literal">port</code></th>
1522 <td>3306</td>
1523 <td>The TCP/IP port of the MySQL server. Must be an integer.</td>
1524 </tr><tr>
1525 <th scope="row"><code class="literal">conn_attrs</code></th>
1526 <td></td>
1527 <td><p>
1528 Standard
1529 <code class="literal">performance_schema.session_connect_attrs</code>
1530 values are sent; use <code class="literal">conn_attrs</code> to
1531 optionally set additional custom connection attributes as
1532 defined by a dictionary such as
1533 <span class="emphasis"><em>config['conn_attrs'] = {"foo":
1534 "bar"}</em></span>.
1535 </p><p>
1536 The c-ext and pure python implementations differ. The
1537 c-ext implementation depends on the mysqlclient library so
1538 its standard conn_attrs values originate from it. For
1539 example, '_client_name' is 'libmysql' with c-ext but
1540 'mysql-connector-python' with pure python. C-ext adds
1541 these additional attributes: '_connector_version',
1542 '_connector_license', '_connector_name', and
1543 '_source_host'.
1544 </p><p>
1545 This option was added in 8.0.17, as was the default
1546 session_connect_attrs behavior.
1547 </p></td>
1548 </tr><tr>
1549 <th scope="row"><code class="literal">init_command</code></th>
1550 <td></td>
1551 <td>Command (SQL query) executed immediately after the connection is
1552 established as part of the initialization process. Added in
1553 8.0.32.</td>
1554 </tr><tr>
1555 <th scope="row"><code class="literal">auth_plugin</code></th>
1556 <td></td>
1557 <td>Authentication plugin to use. Added in 1.2.1.</td>
1558 </tr><tr id="connector-python-connectargs-listing-fido_callback">
1559 <th scope="row"><code class="literal">fido_callback</code></th>
1560 <td></td>
1561 <td><p>
1562 Deprecated as of 8.2.0 and removed in 8.4.0; instead use
1563 <code class="option">webauthn_callback</code>.
1564 </p><p>
1565 A callable defined by the optional
1566 <code class="literal">fido_callback</code> option is executed when
1567 it's ready for user interaction with the hardware FIDO
1568 device. This option can be a callable object or a string
1569 path that the connector can import in runtime and execute.
1570 It does not block and is only used to notify the user of
1571 the need for interaction with the hardware FIDO device.
1572 </p><p>
1573 This functionality was only available in the C extension.
1574 A <span class="emphasis"><em>NotSupportedError</em></span> was raised when
1575 using the pure Python implementation.
1576 </p></td>
1577 </tr><tr id="connector-python-connectargs-listing-webauthn_callback">
1578 <th scope="row"><code class="literal">webauthn_callback</code></th>
1579 <td></td>
1580 <td><p>
1581 A callable defined by the optional
1582 <code class="literal">webauthn_callback</code> option is executed
1583 when it's ready for user interaction with the hardware
1584 WebAuthn device. This option can be a callable object or a
1585 string path that the connector can import in runtime and
1586 execute. It does not block and is only used to notify the
1587 user of the need for interaction with the hardware FIDO
1588 device. Enable the
1589 <code class="literal">authentication_webauthn_client</code>
1590 auth_plugin in the connection configuration to use.
1591 </p><p>
1592 This option was added in 8.2.0, and it deprecated the
1593 <code class="literal">fido_callback</code> option that was removed
1594 in version 8.4.0.
1595 </p></td>
1596 </tr><tr>
1597 <th scope="row"><code class="literal">openid_token_file</code></th>
1598 <td></td>
1599 <td>Path to the file containing the OpenID JWT formatted identity token.
1600 Added in 9.1.0.</td>
1601 </tr><tr>
1602 <th scope="row"><code class="literal">use_unicode</code></th>
1603 <td><code class="literal">True</code></td>
1604 <td>Whether to use Unicode.</td>
1605 </tr><tr>
1606 <th scope="row"><code class="literal">charset</code></th>
1607 <td><code class="literal">utf8mb4</code></td>
1608 <td>Which MySQL character set to use.</td>
1609 </tr><tr>
1610 <th scope="row"><code class="literal">collation</code></th>
1611 <td><code class="literal">utf8mb4_general_ai_ci</code> (is
1612 <code class="literal">utf8_general_ci</code> in 2.x</td>
1613 <td>Which MySQL collation to use. The 8.x default values are generated from
1614 the latest MySQL Server 8.0 defaults.</td>
1615 </tr><tr>
1616 <th scope="row"><code class="literal">autocommit</code></th>
1617 <td><code class="literal">False</code></td>
1618 <td>Whether to <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_autocommit" target="_top">autocommit</a>
1619 transactions.</td>
1620 </tr><tr>
1621 <th scope="row"><code class="literal">time_zone</code></th>
1622 <td></td>
1623 <td>Set the <code class="literal">time_zone</code> session variable at connection
1624 time.</td>
1625 </tr><tr>
1626 <th scope="row"><code class="literal">sql_mode</code></th>
1627 <td></td>
1628 <td>Set the <code class="literal">sql_mode</code> session variable at connection time.</td>
1629 </tr><tr>
1630 <th scope="row"><code class="literal">get_warnings</code></th>
1631 <td><code class="literal">False</code></td>
1632 <td>Whether to fetch warnings.</td>
1633 </tr><tr>
1634 <th scope="row"><code class="literal">raise_on_warnings</code></th>
1635 <td><code class="literal">False</code></td>
1636 <td>Whether to raise an exception on warnings.</td>
1637 </tr><tr>
1638 <th scope="row"><code class="literal">connection_timeout</code>
1639 (<code class="literal">connect_timeout</code>*)</th>
1640 <td></td>
1641 <td>Timeout for the TCP and Unix socket connections.</td>
1642 </tr><tr>
1643 <th scope="row"><code class="literal">read_timeout</code></th>
1644 <td><code class="literal">None</code></td>
1645 <td>Time limit to receive a response from the server before raising a
1646 <code class="literal">ReadTimeoutError</code> level error. The default
1647 value (None) sets the wait time to indefinitely. Option
1648 added in 9.2.0.</td>
1649 </tr><tr>
1650 <th scope="row"><code class="literal">write_timeout</code></th>
1651 <td><code class="literal">None</code></td>
1652 <td>Time limit to send data to the server before raising a
1653 <code class="literal">WriteTimeoutError</code> level error. The
1654 default value (None) sets the wait time to indefinitely.
1655 Option added in 9.2.0.</td>
1656 </tr><tr>
1657 <th scope="row"><code class="literal">client_flags</code></th>
1658 <td></td>
1659 <td>MySQL client flags.</td>
1660 </tr><tr>
1661 <th scope="row"><code class="literal">buffered</code></th>
1662 <td><code class="literal">False</code></td>
1663 <td>Whether cursor objects fetch the results immediately after executing
1664 queries.</td>
1665 </tr><tr>
1666 <th scope="row"><code class="literal">raw</code></th>
1667 <td><code class="literal">False</code></td>
1668 <td>Whether MySQL results are returned as is, rather than converted to
1669 Python types.</td>
1670 </tr><tr>
1671 <th scope="row"><code class="literal">consume_results</code></th>
1672 <td>False</td>
1673 <td>Whether to automatically read result sets.</td>
1674 </tr><tr>
1675 <th scope="row"><code class="literal">tls_versions</code></th>
1676 <td>["TLSv1.2", "TLSv1.3"]</td>
1677 <td>TLS versions to support; allowed versions are TLSv1.2 and TLSv1.3.
1678 Versions TLSv1 and TLSv1.1 were removed in Connector/Python 8.0.28.</td>
1679 </tr><tr>
1680 <th scope="row"><code class="literal">ssl_ca</code></th>
1681 <td></td>
1682 <td>File containing the SSL certificate authority.</td>
1683 </tr><tr>
1684 <th scope="row"><code class="literal">ssl_cert</code></th>
1685 <td></td>
1686 <td>File containing the SSL certificate file.</td>
1687 </tr><tr>
1688 <th scope="row"><code class="literal">ssl_disabled</code></th>
1689 <td><code class="literal">False</code></td>
1690 <td><code class="literal">True</code> disables SSL/TLS usage. The TLSv1 and TLSv1.1
1691 connection protocols are deprecated as of Connector/Python 8.0.26 and
1692 removed as of Connector/Python 8.0.28.</td>
1693 </tr><tr>
1694 <th scope="row"><code class="literal">ssl_key</code></th>
1695 <td></td>
1696 <td>File containing the SSL key.</td>
1697 </tr><tr>
1698 <th scope="row"><code class="literal">ssl_verify_cert</code></th>
1699 <td><code class="literal">False</code></td>
1700 <td>When set to <code class="literal">True</code>, checks the server certificate
1701 against the certificate file specified by the
1702 <code class="literal">ssl_ca</code> option. Any mismatch causes a
1703 <code class="literal">ValueError</code> exception.</td>
1704 </tr><tr>
1705 <th scope="row"><code class="literal">ssl_verify_identity</code></th>
1706 <td><code class="literal">False</code></td>
1707 <td>When set to <code class="literal">True</code>, additionally perform host name
1708 identity verification by checking the host name that the
1709 client uses for connecting to the server against the
1710 identity in the certificate that the server sends to the
1711 client. Option added in Connector/Python 8.0.14.</td>
1712 </tr><tr>
1713 <th scope="row"><code class="literal">force_ipv6</code></th>
1714 <td><code class="literal">False</code></td>
1715 <td>When set to <code class="literal">True</code>, uses IPv6 when an address resolves
1716 to both IPv4 and IPv6. By default, IPv4 is used in such
1717 cases.</td>
1718 </tr><tr>
1719 <th scope="row"><code class="literal">kerberos_auth_mode</code></th>
1720 <td><code class="literal">SSPI</code></td>
1721 <td>Windows-only, for choosing between SSPI and GSSAPI at runtime for the
1722 <code class="literal">authentication_kerberos_client</code>
1723 authentication plugin on Windows. Option added in Connector/Python
1724 8.0.32.</td>
1725 </tr><tr>
1726 <th scope="row"><code class="literal">oci_config_file</code></th>
1727 <td><code class="literal">""</code></td>
1728 <td><p>
1729 Optionally define a specific path to the
1730 <code class="literal">authentication_oci</code> server-side
1731 authentication configuration file. The profile name can be
1732 configured with <code class="literal">oci_config_profile</code>.
1733 </p><p>
1734 The default file path on Linux and macOS is
1735 <code class="literal">~/.oci/config</code>, and
1736 <code class="literal">%HOMEDRIVE%%HOMEPATH%\.oci\config</code> on
1737 Windows.
1738 </p></td>
1739 </tr><tr>
1740 <th scope="row"><code class="literal">oci_config_profile</code></th>
1741 <td><code class="literal">"DEFAULT"</code></td>
1742 <td><p>
1743 Used to specify a profile to use from the OCI
1744 configuration file that contains the generated ephemeral
1745 key pair and security token. The OCI configuration file
1746 location can be defined by
1747 <code class="literal">oci_config_file</code>. Option
1748 <code class="literal">oci_config_profile</code> was added in Connector/Python
1749 8.0.33.
1750 </p></td>
1751 </tr><tr>
1752 <th scope="row"><code class="literal">dsn</code></th>
1753 <td></td>
1754 <td>Not supported (raises <code class="literal">NotSupportedError</code> when used).</td>
1755 </tr><tr>
1756 <th scope="row"><code class="literal">pool_name</code></th>
1757 <td></td>
1758 <td>Connection pool name. The pool name is restricted to alphanumeric
1759 characters and the special characters <code class="literal">.</code>,
1760 <code class="literal">_</code>, <code class="literal">*</code>,
1761 <code class="literal">$</code>, and <code class="literal">#</code>. The pool
1762 name must be no more than
1763 <code class="literal">pooling.CNX_POOL_MAXNAMESIZE</code> characters
1764 long (default 64).</td>
1765 </tr><tr>
1766 <th scope="row"><code class="literal">pool_size</code></th>
1767 <td>5</td>
1768 <td>Connection pool size. The pool size must be greater than 0 and less than
1769 or equal to <code class="literal">pooling.CNX_POOL_MAXSIZE</code>
1770 (default 32).</td>
1771 </tr><tr>
1772 <th scope="row"><code class="literal">pool_reset_session</code></th>
1773 <td><code class="literal">True</code></td>
1774 <td>Whether to reset session variables when connection is returned to pool.</td>
1775 </tr><tr>
1776 <th scope="row"><code class="literal">compress</code></th>
1777 <td><code class="literal">False</code></td>
1778 <td>Whether to use compressed client/server protocol.</td>
1779 </tr><tr>
1780 <th scope="row"><code class="literal">converter_class</code></th>
1781 <td></td>
1782 <td>Converter class to use.</td>
1783 </tr><tr>
1784 <th scope="row"><code class="literal">converter_str_fallback</code></th>
1785 <td><code class="literal">False</code></td>
1786 <td>Enable the conversion to str of value types not supported by the
1787 Connector/Python converter class or by a custom converter
1788 class.</td>
1789 </tr><tr>
1790 <th scope="row"><code class="literal">failover</code></th>
1791 <td></td>
1792 <td>Server failover sequence.</td>
1793 </tr><tr>
1794 <th scope="row"><code class="literal">option_files</code></th>
1795 <td></td>
1796 <td>Which option files to read. Added in 2.0.0.</td>
1797 </tr><tr>
1798 <th scope="row"><code class="literal">option_groups</code></th>
1799 <td><code class="literal">['client', 'connector_python']</code></td>
1800 <td>Which groups to read from option files. Added in 2.0.0.</td>
1801 </tr><tr>
1802 <th scope="row"><code class="literal">allow_local_infile</code></th>
1803 <td><code class="literal">True</code></td>
1804 <td>Whether to enable <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/load-data.html" target="_top"><code class="literal">LOAD DATA
1805 LOCAL INFILE</code></a>. Added in 2.0.0.</td>
1806 </tr><tr>
1807 <th scope="row"><code class="literal">use_pure</code></th>
1808 <td><code class="literal">False</code> as of 8.0.11, and <code class="literal">True</code> in
1809 earlier versions. If only one implementation (C or Python)
1810 is available, then then the default value is set to enable
1811 the available implementation.</td>
1812 <td>Whether to use pure Python or C Extension. If
1813 <code class="literal">use_pure=False</code> and the C Extension is not
1814 available, then Connector/Python will automatically fall
1815 back to the pure Python implementation. Can be set with
1816 <span class="emphasis"><em>mysql.connector.connect()</em></span> but not
1817 <span class="emphasis"><em>MySQLConnection.connect()</em></span>. Added in
1818 2.1.1.</td>
1819 </tr><tr>
1820 <th scope="row"><code class="literal">krb_service_principal</code></th>
1821 <td>The "@realm" defaults to the default realm, as configured in the
1822 <code class="filename">krb5.conf</code> file.</td>
1823 <td>Must be a string in the form "primary/instance@realm" such as
1824 "ldap/[email protected]" where "@realm" is optional. Added
1825 in 8.0.23.</td>
1826 </tr></tbody></table></div></div><br class="table-break"><h3><a name="id2624"></a>MySQL Authentication Options</h3><p>
1827 Authentication with MySQL typically uses a
1828 <code class="literal">username</code> and <code class="literal">password</code>.
1829 </p><p>
1830 When the <code class="literal">database</code> argument is given, the
1831 current database is set to the given value. To change the current
1832 database later, execute a <code class="literal">USE</code> SQL statement or
1833 set the <code class="literal">database</code> property of the
1834 <code class="literal">MySQLConnection</code> instance.
1835 </p><p>
1836 By default, Connector/Python tries to connect to a MySQL server running on
1837 the local host using TCP/IP. The <code class="literal">host</code> argument
1838 defaults to IP address 127.0.0.1 and <code class="literal">port</code> to
1839 3306. Unix sockets are supported by setting
1840 <code class="literal">unix_socket</code>. Named pipes on the Windows
1841 platform are not supported.
1842 </p><p>
1843 Connector/Python supports authentication plugins available as of MySQL 8.0,
1844 including the preferred
1845 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/caching-sha2-pluggable-authentication.html" target="_top">caching_sha2_password</a>
1846 authentication plugin.
1847 </p><p>
1848 The deprecated
1849 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/native-pluggable-authentication.html" target="_top">mysql_native_password</a>
1850 plugin is supported, but it is disabled by default as of MySQL
1851 Server 8.4.0 and removed as of MySQL Server 9.0.0.
1852 </p><p>
1853 The <code class="literal">connect()</code> method supports an
1854 <code class="literal">auth_plugin</code> argument that can be used to force
1855 use of a particular authentication plugin.
1856 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
1857 MySQL Connector/Python does not support the old, less-secure password protocols
1858 of MySQL versions prior to 4.1.
1859 </p></div><p>
1860 Connector/Python supports the
1861 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/kerberos-pluggable-authentication.html" target="_top">Kerberos
1862 authentication protocol</a> for passwordless authentication.
1863 Linux clients are supported as of Connector/Python 8.0.26, and Windows
1864 support was added in Connector/Python 8.0.27 with the C extension
1865 implementation, and in Connector/Python 8.0.29 with the pure Python
1866 implementation. For Windows, the related
1867 <code class="option">kerberos_auth_mode</code> connection option was added in
1868 8.0.32 to configure the mode as either SSPI (default) or GSSAPI
1869 (via the pure Python implementation, or the C extension
1870 implementation as of 8.4.0). While Windows supports both modes,
1871 Linux only supports GSSAPI.
1872 </p><p>
1873 Optionally use the <code class="literal">[gssapi]</code> shortcut when
1874 installing the <code class="literal">mysql-connector-python</code> pip
1875 package to pull in specific GSSAPI versions as defined by the
1876 connector, which is v1.8.3 as of Connector/Python 9.1.0:
1877 </p><pre class="programlisting">$ pip install mysql-connector-python[gssapi]
1878 </pre><p>
1879 The following example assumes
1880 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/ldap-pluggable-authentication.html" target="_top">LDAP Pluggable Authentication</a> is set up to
1881 utilize GSSAPI/Kerberos SASL authentication:
1882 </p><pre data-lang="python" class="programlisting">import mysql.connector as cpy
1883 import logging
1884
1885 logging.basicConfig(level=logging.DEBUG)
1886
1887 SERVICE_NAME = "ldap"
1888 LDAP_SERVER_IP = "server_ip or hostname" # e.g., winexample01
1889
1890 config = {
1891 "host": "127.0.0.1",
1892 "port": 3306,
1893 "user": "[email protected]",
1894 "password": "s3cret",
1895 "use_pure": True,
1896 "krb_service_principal": f"{SERVICE_NAME}/{LDAP_SERVER_IP}"
1897 }
1898
1899 with cpy.connect(**config) as cnx:
1900 with cnx.cursor() as cur:
1901 cur.execute("SELECT @@version")
1902 res = cur.fetchone()
1903 print(res[0])
1904 </pre><p>
1905 Connector/Python supports Multi-Factor Authentication (MFA) as of v8.0.28 by
1906 utilizing the <code class="option">password1</code> (alias of
1907 <code class="option">password</code>), <code class="option">password2</code>, and
1908 <code class="option">password3</code> connection options.
1909 </p><p>
1910 Connector/Python supports
1911 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.4/en/webauthn-pluggable-authentication.html" target="_top">WebAuthn
1912 Pluggable Authentication</a> as of Connector/Python 8.2.0, which is
1913 supported in MySQL Enterprise Edition. Optionally use the Connector/Python
1914 <a class="link" href="#connector-python-connectargs-listing-webauthn_callback">webauthn_callback</a>
1915 connection option to notify users that they need to touch the
1916 hardware device. This functionality is present in the C
1917 implementation (which uses libmysqlclient) but the pure Python
1918 implementation requires the FIDO2 dependency that is not provided
1919 with the MySQL connector and is assumed to already be present in
1920 your environment. It can be independently installed using:
1921 </p><pre data-lang="terminal" class="programlisting">$&gt; pip install fido2
1922 </pre><p>
1923 Previously, the now removed (as of version 8.4.0)
1924 <code class="literal">authentication_fido</code> MySQL Server plugin was
1925 supported using the
1926 <a class="link" href="#connector-python-connectargs-listing-fido_callback">fido_callback</a>
1927 option that was available in the C extension implementation.
1928 </p><p>
1929 Connector/Python supports <span class="emphasis"><em>OpenID Connect</em></span> as of Connector/Python
1930 9.1.0. Functionality is enabled with the
1931 <code class="literal">authentication_openid_connect_client</code>
1932 client-side authentication plugin connecting to MySQL Enterprise Edition with the
1933 <code class="literal">authentication_openid_connect</code> authentication
1934 plugin. These examples enable the plugin with
1935 <code class="literal">auth_plugin</code> and defines the JWT Identity Token
1936 file location with <code class="literal">openid_token_file</code>:
1937 </p><pre data-lang="python" class="programlisting"># Standard connection
1938 import mysql.connector as cpy
1939 config = {
1940 "host": "localhost",
1941 "port": 3306,
1942 "user": "root",
1943 "openid_token_file": "{path-to-id-token-file}",
1944 "auth_plugin": "authentication_openid_connect_client",
1945 "use_pure": True, # Use False for C-Extension
1946 }
1947 with cpy.connect(**config) as cnx:
1948 with cnx.cursor() as cur:
1949 cur.execute("SELECT @@version")
1950 print(cur.fetchall())
1951
1952 # Or, using an async connection
1953 import mysql.connector.aio as cpy_async
1954 import asyncio
1955 config = {
1956 "host": "localhost",
1957 "port": 3306,
1958 "user": "root",
1959 "auth_plugin": "authentication_openid_connect_client",
1960 "openid_token_file": "{path-to-id-token-file}",
1961 }
1962 async def test():
1963 async with await cpy_async.connect(**config) as cnx:
1964 async with await cnx.cursor() as cur:
1965 await cur.execute("SELECT @@version")
1966 print(await cur.fetchall())
1967 asyncio.run(test())
1968 </pre><h3><a name="id2677"></a>Character Encoding</h3><p>
1969 By default, strings coming from MySQL are returned as Python
1970 Unicode literals. To change this behavior, set
1971 <code class="literal">use_unicode</code> to <code class="literal">False</code>. You
1972 can change the character setting for the client connection through
1973 the <code class="literal">charset</code> argument. To change the character
1974 set after connecting to MySQL, set the <code class="literal">charset</code>
1975 property of the <code class="literal">MySQLConnection</code> instance. This
1976 technique is preferred over using the <code class="literal">SET NAMES</code>
1977 SQL statement directly. Similar to the <code class="literal">charset</code>
1978 property, you can set the <code class="literal">collation</code> for the
1979 current MySQL session.
1980 </p><h3><a name="id2687"></a>Transactions</h3><p>
1981 The <code class="literal">autocommit</code> value defaults to
1982 <code class="literal">False</code>, so transactions are not automatically
1983 committed. Call the <code class="literal">commit()</code> method of the
1984 <code class="literal">MySQLConnection</code> instance within your
1985 application after doing a set of related insert, update, and
1986 delete operations. For data consistency and high throughput for
1987 write operations, it is best to leave the
1988 <code class="literal">autocommit</code> configuration option turned off when
1989 using <code class="literal">InnoDB</code> or other transactional tables.
1990 </p><h3><a name="id2695"></a>Time Zones</h3><p>
1991 The time zone can be set per connection using the
1992 <code class="literal">time_zone</code> argument. This is useful, for
1993 example, if the MySQL server is set to UTC and
1994 <code class="literal">TIMESTAMP</code> values should be returned by MySQL
1995 converted to the <code class="literal">PST</code> time zone.
1996 </p><h3><a name="id2700"></a>SQL Modes</h3><p>
1997 MySQL supports so-called SQL Modes. which change the behavior of
1998 the server globally or per connection. For example, to have
1999 warnings raised as errors, set <code class="literal">sql_mode</code> to
2000 <code class="literal">TRADITIONAL</code>. For more information, see
2001 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html" target="_top">Server SQL Modes</a>.
2002 </p><h3><a name="id2705"></a>Troubleshooting and Error Handling</h3><p>
2003 Warnings generated by queries are fetched automatically when
2004 <code class="literal">get_warnings</code> is set to <code class="literal">True</code>.
2005 You can also immediately raise an exception by setting
2006 <code class="literal">raise_on_warnings</code> to <code class="literal">True</code>.
2007 Consider using the MySQL <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html" target="_top">sql_mode</a>
2008 setting for turning warnings into errors.
2009 </p><p>
2010 To set a timeout value for connections, use
2011 <code class="literal">connection_timeout</code>.
2012 </p><h3><a name="id2714"></a>Enabling and Disabling Features Using Client Flags</h3><p>
2013 MySQL uses <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-real-connect.html" target="_top">client flags</a>
2014 to enable or disable features. Using the
2015 <code class="literal">client_flags</code> argument, you have control of what
2016 is set. To find out what flags are available, use the following:
2017 </p><pre data-lang="python" class="programlisting">from mysql.connector.constants import ClientFlag
2018 print '\n'.join(ClientFlag.get_full_info())
2019 </pre><p>
2020 If <code class="literal">client_flags</code> is not specified (that is, it
2021 is zero), defaults are used for MySQL 4.1 and higher. If you
2022 specify an integer greater than <code class="literal">0</code>, make sure
2023 all flags are set properly. A better way to set and unset flags
2024 individually is to use a list. For example, to set
2025 <code class="literal">FOUND_ROWS</code>, but disable the default
2026 <code class="literal">LONG_FLAG</code>:
2027 </p><pre data-lang="python" class="programlisting">flags = [ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG]
2028 mysql.connector.connect(client_flags=flags)
2029 </pre><h3><a name="id2725"></a>Result Set Handling</h3><p>
2030 By default, MySQL Connector/Python does not buffer or prefetch results. This means
2031 that after a query is executed, your program is responsible for
2032 fetching the data. This avoids excessive memory use when queries
2033 return large result sets. If you know that the result set is small
2034 enough to handle all at once, you can fetch the results
2035 immediately by setting <code class="literal">buffered</code> to
2036 <code class="literal">True</code>. It is also possible to set this per
2037 cursor (see
2038 <a class="xref" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method">Section 10.2.6, “MySQLConnection.cursor() Method”</a>).
2039 </p><p>
2040 Results generated by queries normally are not read until the
2041 client program fetches them. To automatically consume and discard
2042 result sets, set the <code class="literal">consume_results</code> option to
2043 <code class="literal">True</code>. The result is that all results are read,
2044 which for large result sets can be slow. (In this case, it might
2045 be preferable to close and reopen the connection.)
2046 </p><h3><a name="id2733"></a>Type Conversions</h3><p>
2047 By default, MySQL types in result sets are converted automatically
2048 to Python types. For example, a <code class="literal">DATETIME</code> column
2049 value becomes a
2050 <a class="ulink" href="http://docs.python.org/library/datetime.html#datetime.datetime" target="_top">datetime.datetime</a>
2051 object. To disable conversion, set the <code class="literal">raw</code>
2052 option to <code class="literal">True</code>. You might do this to get better
2053 performance or perform different types of conversion yourself.
2054 </p><h3><a name="id2739"></a>Connecting through SSL</h3><p>
2055 Using SSL connections is possible when your
2056 <a class="ulink" href="http://docs.python.org/library/ssl.html" target="_top">Python
2057 installation supports SSL</a>, that is, when it is compiled
2058 against the OpenSSL libraries. When you provide the
2059 <code class="literal">ssl_ca</code>, <code class="literal">ssl_key</code> and
2060 <code class="literal">ssl_cert</code> options, the connection switches to
2061 SSL, and the <code class="literal">client_flags</code> option includes the
2062 <code class="literal">ClientFlag.SSL</code> value automatically. You can use
2063 this in combination with the <code class="literal">compressed</code> option
2064 set to <code class="literal">True</code>.
2065 </p><p>
2066 As of Connector/Python 2.2.2, if the MySQL server supports SSL connections,
2067 Connector/Python attempts to establish a secure (encrypted) connection by
2068 default, falling back to an unencrypted connection otherwise.
2069 </p><p>
2070 From Connector/Python 1.2.1 through Connector/Python 2.2.1, it is possible to establish
2071 an SSL connection using only the <code class="literal">ssl_ca</code> opion.
2072 The <code class="literal">ssl_key</code> and <code class="literal">ssl_cert</code>
2073 arguments are optional. However, when either is given, both must
2074 be given or an <code class="literal">AttributeError</code> is raised.
2075 </p><pre data-lang="python" class="programlisting"># Note (Example is valid for Python v2 and v3)
2076 from __future__ import print_function
2077
2078 import sys
2079
2080 #sys.path.insert(0, 'python{0}/'.format(sys.version_info[0]))
2081
2082 import mysql.connector
2083 from mysql.connector.constants import ClientFlag
2084
2085 config = {
2086 'user': 'ssluser',
2087 'password': '<em class="replaceable"><code>password</code></em>',
2088 'host': '127.0.0.1',
2089 'client_flags': [ClientFlag.SSL],
2090 'ssl_ca': '/opt/mysql/ssl/ca.pem',
2091 'ssl_cert': '/opt/mysql/ssl/client-cert.pem',
2092 'ssl_key': '/opt/mysql/ssl/client-key.pem',
2093 }
2094
2095 cnx = mysql.connector.connect(**config)
2096 cur = cnx.cursor(buffered=True)
2097 cur.execute("SHOW STATUS LIKE 'Ssl_cipher'")
2098 print(cur.fetchone())
2099 cur.close()
2100 cnx.close()
2101 </pre><h3><a name="id2758"></a>Connection Pooling</h3><p>
2102 With either the <code class="literal">pool_name</code> or
2103 <code class="literal">pool_size</code> argument present, Connector/Python creates the
2104 new pool. If the <code class="literal">pool_name</code> argument is not
2105 given, the <code class="literal">connect()</code> call automatically
2106 generates the name, composed from whichever of the
2107 <code class="literal">host</code>, <code class="literal">port</code>,
2108 <code class="literal">user</code>, and <code class="literal">database</code>
2109 connection arguments are given, in that order. If the
2110 <code class="literal">pool_size</code> argument is not given, the default
2111 size is 5 connections.
2112 </p><p>
2113 The <code class="literal">pool_reset_session</code> permits control over
2114 whether session variables are reset when the connection is
2115 returned to the pool. The default is to reset them.
2116 </p><p>
2117 For additional information about connection pooling, see
2118 <a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>.
2119 </p><h3><a name="id2773"></a>Protocol Compression</h3><p>
2120 The boolean <code class="literal">compress</code> argument indicates whether
2121 to use the compressed client/server protocol (default
2122 <code class="literal">False</code>). This provides an easier alternative to
2123 setting the <code class="literal">ClientFlag.COMPRESS</code> flag. This
2124 argument is available as of Connector/Python 1.1.2.
2125 </p><h3><a name="id2778"></a>Converter Class</h3><p>
2126 The <code class="literal">converter_class</code> argument takes a class and
2127 sets it when configuring the connection. An
2128 <code class="literal">AttributeError</code> is raised if the custom
2129 converter class is not a subclass of
2130 <code class="literal">conversion.MySQLConverterBase</code>.
2131 </p><h3><a name="id2783"></a>Server Failover</h3><p>
2132 The <code class="literal">connect()</code> method accepts a
2133 <code class="literal">failover</code> argument that provides information to
2134 use for server failover in the event of connection failures. The
2135 argument value is a tuple or list of dictionaries (tuple is
2136 preferred because it is nonmutable). Each dictionary contains
2137 connection arguments for a given server in the failover sequence.
2138 Permitted dictionary values are: <code class="literal">user</code>,
2139 <code class="literal">password</code>, <code class="literal">host</code>,
2140 <code class="literal">port</code>, <code class="literal">unix_socket</code>,
2141 <code class="literal">database</code>, <code class="literal">pool_name</code>,
2142 <code class="literal">pool_size</code>. This failover option was added in
2143 Connector/Python 1.2.1.
2144 </p><h3><a name="id2795"></a>Option File Support</h3><p>
2145 As of Connector/Python 2.0.0, option files are supported using two options
2146 for <code class="literal">connect()</code>:
2147 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
2148 <code class="literal">option_files</code>: Which option files to read.
2149 The value can be a file path name (a string) or a sequence of
2150 path name strings. By default, Connector/Python reads no option files, so
2151 this argument must be given explicitly to cause option files
2152 to be read. Files are read in the order specified.
2153 </p></li><li class="listitem"><p>
2154 <code class="literal">option_groups</code>: Which groups to read from
2155 option files, if option files are read. The value can be an
2156 option group name (a string) or a sequence of group name
2157 strings. If this argument is not given, the default value is
2158 <code class="literal">['client', 'connector_python']</code> to read the
2159 <code class="literal">[client]</code> and
2160 <code class="literal">[connector_python]</code> groups.
2161 </p></li></ul></div><p>
2162 For more information, see
2163 <a class="xref" href="#connector-python-option-files" title="7.2 Connector/Python Option-File Support">Section 7.2, “Connector/Python Option-File Support”</a>.
2164 </p><h3><a name="id2810"></a>LOAD DATA LOCAL INFILE</h3><p>
2165 Prior to Connector/Python 2.0.0, to enable use of
2166 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/load-data.html" target="_top"><code class="literal">LOAD DATA LOCAL
2167 INFILE</code></a>, clients had to explicitly set the
2168 <code class="literal">ClientFlag.LOCAL_FILES</code> flag. As of 2.0.0, this
2169 flag is enabled by default. To disable it, the
2170 <code class="literal">allow_local_infile</code> connection option can be set
2171 to <code class="literal">False</code> at connect time (the default is
2172 <code class="literal">True</code>).
2173 </p><h3><a name="id2818"></a>Compatibility with Other Connection Interfaces</h3><p>
2174 <code class="literal">passwd</code>, <code class="literal">db</code> and
2175 <code class="literal">connect_timeout</code> are valid for compatibility
2176 with other MySQL interfaces and are respectively the same as
2177 <code class="literal">password</code>, <code class="literal">database</code> and
2178 <code class="literal">connection_timeout</code>. The latter take precedence.
2179 Data source name syntax or <code class="literal">dsn</code> is not used; if
2180 specified, it raises a <code class="literal">NotSupportedError</code>
2181 exception.
2182 </p><h3><a name="id2828"></a>Client/Server Protocol Implementation</h3><p>
2183 Connector/Python can use a pure Python interface to MySQL, or a C Extension
2184 that uses the MySQL C client library. The
2185 <code class="literal">use_pure</code>
2186 <span class="emphasis"><em>mysql.connector.connect()</em></span> connection argument
2187 determines which. The default changed in Connector/Python 8 from
2188 <code class="literal">True</code> (use the pure Python implementation) to
2189 <code class="literal">False</code>. Setting <code class="literal">use_pure</code>
2190 changes the implementation used.
2191 </p><p>
2192 The <code class="literal">use_pure</code> argument is available as of Connector/Python
2193 2.1.1. For more information about the C extension, see
2194 <a class="xref" href="#connector-python-cext" title="Chapter 8 The Connector/Python C Extension">Chapter 8, <i>The Connector/Python C Extension</i></a>.
2195 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-option-files"></a>7.2 Connector/Python Option-File Support</h2></div></div></div><p>
2196 Connector/Python can read options from option files. (For general information
2197 about option files in MySQL, see <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/option-files.html" target="_top">Using Option Files</a>.)
2198 Two arguments for the <code class="literal">connect()</code> call control
2199 use of option files in Connector/Python programs:
2200 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
2201 <code class="literal">option_files</code>: Which option files to read.
2202 The value can be a file path name (a string) or a sequence of
2203 path name strings. By default, Connector/Python reads no option files, so
2204 this argument must be given explicitly to cause option files
2205 to be read. Files are read in the order specified.
2206 </p></li><li class="listitem"><p>
2207 <code class="literal">option_groups</code>: Which groups to read from
2208 option files, if option files are read. The value can be an
2209 option group name (a string) or a sequence of group name
2210 strings. If this argument is not given, the default value is
2211 <code class="literal">['client', 'connector_python']</code>, to read the
2212 <code class="literal">[client]</code> and
2213 <code class="literal">[connector_python]</code> groups.
2214 </p></li></ul></div><p>
2215 Connector/Python also supports the <code class="literal">!include</code> and
2216 <code class="literal">!includedir</code> inclusion directives within option
2217 files. These directives work the same way as for other MySQL
2218 programs (see <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/option-files.html" target="_top">Using Option Files</a>).
2219 </p><p>
2220 This example specifies a single option file as a string:
2221 </p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf')
2222 </pre><p>
2223 This example specifies multiple option files as a sequence of
2224 strings:
2225 </p><pre data-lang="python" class="programlisting">mysql_option_files = [
2226 '/etc/mysql/connectors.cnf',
2227 './development.cnf',
2228 ]
2229 cnx = mysql.connector.connect(option_files=mysql_option_files)
2230 </pre><p>
2231 Connector/Python reads no option files by default, for backward compatibility
2232 with versions older than 2.0.0. This differs from standard MySQL
2233 clients such as <span class="command"><strong>mysql</strong></span> or
2234 <span class="command"><strong>mysqldump</strong></span>, which do read option files by
2235 default. To find out which option files the standard clients read
2236 on your system, invoke one of them with its
2237 <code class="option">--help</code> option and examine the output. For
2238 example:
2239 </p><pre data-lang="terminal" class="programlisting">$&gt; <strong class="userinput"><code>mysql --help</code></strong>
2240 ...
2241 Default options are read from the following files in the given order:
2242 /etc/my.cnf /etc/mysql/my.cnf /usr/local/mysql/etc/my.cnf ~/.my.cnf
2243 ...
2244 </pre><p>
2245 If you specify the <code class="literal">option_files</code> connection
2246 argument to read option files, Connector/Python reads the
2247 <code class="literal">[client]</code> and
2248 <code class="literal">[connector_python]</code> option groups by default. To
2249 specify explicitly which groups to read, use the
2250 <code class="literal">option_groups</code> connection argument. The
2251 following example causes only the
2252 <code class="literal">[connector_python]</code> group to be read:
2253 </p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf',
2254 option_groups='connector_python')
2255 </pre><p>
2256 Other connection arguments specified in the
2257 <code class="literal">connect()</code> call take precedence over options
2258 read from option files. Suppose that
2259 <code class="filename">/etc/mysql/connectors.conf</code> contains these
2260 lines:
2261 </p><pre data-lang="ini" class="programlisting">[client]
2262 database=cpyapp
2263 </pre><p>
2264 The following <code class="literal">connect()</code> call includes no
2265 <code class="literal">database</code> connection argument. The resulting
2266 connection uses <code class="literal">cpyapp</code>, the database specified
2267 in the option file:
2268 </p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf')
2269 </pre><p>
2270 By contrast, the following <code class="literal">connect()</code> call
2271 specifies a default database different from the one found in the
2272 option file. The resulting connection uses
2273 <code class="literal">cpyapp_dev</code> as the default database, not
2274 <code class="literal">cpyapp</code>:
2275 </p><pre data-lang="python" class="programlisting">cnx2 = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf',
2276 database='cpyapp_dev')
2277 </pre><p>
2278 Connector/Python raises a <code class="literal">ValueError</code> if an option file
2279 cannot be read, or has already been read. This includes files read
2280 by inclusion directives.
2281 </p><p>
2282 For the <code class="literal">[connector_python]</code> group, only options
2283 supported by Connector/Python are accepted. Unrecognized options cause a
2284 <code class="literal">ValueError</code> to be raised.
2285 </p><p>
2286 For other option groups, Connector/Python ignores unrecognized options.
2287 </p><p>
2288 It is not an error for a named option group not to exist.
2289 </p><h3><a name="id2896"></a>Option Parsing</h3><p>
2290 Connector/Python reads the option values in option files as strings, and
2291 attempts to parse them using Python's
2292 <code class="literal">ast.literal_eval</code> function. This allows
2293 specifying values like numbers, tuples, lists, and booleans in the
2294 option files. If a value can't be parsed by
2295 <code class="literal">ast.literal_eval</code> then it's passed as a literal
2296 string.
2297 </p><p>
2298 For example, this option file has options with values using a
2299 number, a string, and a tuple of dictionaries that are correctly
2300 parsed for the <code class="literal">[connector_python]</code> group:
2301 </p><pre data-lang="ini" class="programlisting">[connector_python]
2302 database=cpyapp
2303 port=3656
2304 failover=({'host': '203.0.113.1', 'port': 3640}, {'host': '203.0.113.101', 'port': 3650})
2305 </pre><p>
2306 For additional information, review Python's
2307 <a class="ulink" href="https://docs.python.org/3/library/ast.html#ast.literal_eval" target="_top">ast.literal_eval</a>
2308 documentation including how to handle unsanitized data that could
2309 crash the Python interpreter. Confirm that the option file values
2310 are trustworthy and valid before parsing.
2311 </p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-cext"></a>Chapter 8 The Connector/Python C Extension</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-cext-development">8.1 Application Development with the Connector/Python C Extension</a></span></dt><dt><span class="section"><a href="#connector-python-cext-module">8.2 The _mysql_connector C Extension Module</a></span></dt></dl></div><p>
2312 Connector/Python supports a C extension that interfaces with the MySQL C client
2313 library. For queries that return large result sets, using the C
2314 Extension can improve performance compared to a <span class="quote">“<span class="quote">pure
2315 Python</span>”</span> implementation of the MySQL client/server protocol.
2316 <a class="xref" href="#connector-python-cext-development" title="8.1 Application Development with the Connector/Python C Extension">Section 8.1, “Application Development with the Connector/Python C Extension”</a>, describes how
2317 applications that use the <code class="literal">mysql.connector</code> module
2318 can use the C Extension. It is also possible to use the C Extension
2319 directly, by importing the <code class="literal">_mysql_connector</code>
2320 module rather than the <code class="literal">mysql.connector</code> module.
2321 See <a class="xref" href="#connector-python-cext-module" title="8.2 The _mysql_connector C Extension Module">Section 8.2, “The _mysql_connector C Extension Module”</a>. For information
2322 about installing the C Extension, see
2323 <a class="xref" href="#connector-python-installation" title="Chapter 4 Connector/Python Installation">Chapter 4, <i>Connector/Python Installation</i></a>.
2324 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
2325 The C extension was added in version 2.1.1 and is enabled by
2326 default as of 8.0.11. The <code class="literal">use_pure</code> option
2327 determines whether the Python or C version of this connector is
2328 enabled and used.
2329 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-cext-development"></a>8.1 Application Development with the Connector/Python C Extension</h2></div></div></div><p>
2330 Installations of Connector/Python from version 2.1.1 on support a
2331 <code class="literal">use_pure</code> argument to
2332 <code class="literal">mysql.connector.connect()</code> that indicates
2333 whether to use the pure Python interface to MySQL or the C
2334 Extension that uses the MySQL C client library:
2335 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
2336 By default, <code class="literal">use_pure</code> (use the pure Python
2337 implementation) is <code class="literal">False</code> as of MySQL 8 and
2338 defaults to <code class="literal">True</code> in earlier versions. If
2339 the C extension is not available on the system then
2340 <code class="literal">use_pure</code> is <code class="literal">True</code>.
2341 </p></li><li class="listitem"><p>
2342 On Linux, the C and Python implementations are available as
2343 different packages. You can install one or both
2344 implementations on the same system. On Windows and macOS, the
2345 packages include both implementations.
2346 </p><p>
2347 For Connector/Python installations that include both implementations, it
2348 can optionally be toggled it by passing
2349 <code class="literal">use_pure=False</code> (to use C implementation) or
2350 <code class="literal">use_pure=True</code> (to use the Python
2351 implementation) as an argument to
2352 <code class="literal">mysql.connector.connect()</code>.
2353 </p></li><li class="listitem"><p>
2354 For Connector/Python installations that do not include the C Extension,
2355 passing <code class="literal">use_pure=False</code> to
2356 <code class="literal">mysql.connector.connect()</code> raises an
2357 exception.
2358 </p></li><li class="listitem"><p>
2359 For older Connector/Python installations that know nothing of the C
2360 Extension (before version 2.1.1), passing
2361 <code class="literal">use_pure</code> to
2362 <code class="literal">mysql.connector.connect()</code> raises an
2363 exception regardless of its value.
2364 </p></li></ul></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
2365 On macOS, if your Connector/Python installation includes the C Extension,
2366 but Python scripts are unable to use it, try setting your
2367 <code class="literal">DYLD_LIBRARY_PATH</code> environment variable the
2368 directory containing the C client library. For example:
2369 </p><a class="indexterm" name="id2948"></a><a class="indexterm" name="id2950"></a><pre data-lang="terminal" class="programlisting">export DYLD_LIBRARY_PATH=/usr/local/mysql/lib (for sh)
2370 setenv DYLD_LIBRARY_PATH /usr/local/mysql/lib (for tcsh)
2371 </pre><p>
2372 If you built the C Extension from source, this directory should
2373 be the one containing the C client library against which the
2374 extension was built.
2375 </p></div><p>
2376 If you need to check whether your Connector/Python installation is aware of
2377 the C Extension, test the <code class="literal">HAVE_CEXT</code> value.
2378 There are different approaches for this. Suppose that your usual
2379 arguments for <code class="literal">mysql.connector.connect()</code> are
2380 specified in a dictionary:
2381 </p><pre data-lang="python" class="programlisting">config = {
2382 'user': 'scott',
2383 'password': '<em class="replaceable"><code>password</code></em>',
2384 'host': '127.0.0.1',
2385 'database': 'employees',
2386 }
2387 </pre><p>
2388 The following example illustrates one way to add
2389 <code class="literal">use_pure</code> to the connection arguments:
2390 </p><pre data-lang="python" class="programlisting">import mysql.connector
2391
2392 if mysql.connector.__version_info__ &gt; (2, 1) and mysql.connector.HAVE_CEXT:
2393 config['use_pure'] = False
2394 </pre><p>
2395 If <code class="literal">use_pure=False</code> and the C Extension is not
2396 available, then Connector/Python will automatically fall back to
2397 the pure Python implementation.
2398 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-cext-module"></a>8.2 The _mysql_connector C Extension Module</h2></div></div></div><p>
2399 To use the C Extension directly, import the
2400 <code class="literal">_mysql_connector</code> module rather than
2401 <code class="literal">mysql.connector</code>, then use the
2402 <code class="literal">_mysql_connector.MySQL()</code> class to obtain a
2403 <code class="literal">MySQL</code> instance. For example:
2404 </p><pre data-lang="python" class="programlisting">import _mysql_connector
2405
2406 ccnx = _mysql_connector.MySQL()
2407 ccnx.connect(user='scott', password='<em class="replaceable"><code>password</code></em>',
2408 host='127.0.0.1', database='employees')
2409
2410 ccnx.query("SHOW VARIABLES LIKE 'version%'")
2411 row = ccnx.fetch_row()
2412 while row:
2413 print(row)
2414 row = ccnx.fetch_row()
2415 ccnx.free_result()
2416
2417 ccnx.close()
2418 </pre><p>
2419 For more information, see
2420 <a class="xref" href="#connector-python-cext-reference" title="Chapter 11 Connector/Python C Extension API Reference">Chapter 11, <i>Connector/Python C Extension API Reference</i></a>.
2421 </p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-other"></a>Chapter 9 Connector/Python Other Topics</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-logging">9.1 Connector/Python Logging</a></span></dt><dt><span class="section"><a href="#connector-python-opentelemetry">9.2 Telemetry Support</a></span></dt><dt><span class="section"><a href="#connector-python-multi">9.3 Executing Multiple Statements</a></span></dt><dt><span class="section"><a href="#connector-python-asyncio">9.4 Asynchronous Connectivity</a></span></dt><dt><span class="section"><a href="#connector-python-connection-pooling">9.5 Connector/Python Connection Pooling</a></span></dt><dt><span class="section"><a href="#connector-python-django-backend">9.6 Connector/Python Django Back End</a></span></dt></dl></div><p></p><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-logging"></a>9.1 Connector/Python Logging</h2></div></div></div><p>
2422 By default, logging functionality follows the default Python
2423 logging behavior. If logging functionality is not configured, only
2424 events with a severity level of WARNING and greater are printed to
2425 sys.stderr. For related information, see Python's
2426 <a class="ulink" href="https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library" target="_top">Configuring
2427 Logging for a Library</a> documentation.
2428 </p><p>
2429 Outputting additional levels requires configuration. For example,
2430 to output debug events to sys.stderr set logging.DEBUG and add the
2431 logging.StreamHandler handler. Additional handles can also be
2432 added, such as logging.FileHandler. This example sets both:
2433 </p><pre data-lang="python" class="programlisting"># Classic Protocol Example
2434 import logging
2435 import mysql.connector
2436
2437 logger = logging.getLogger("mysql.connector")
2438 logger.setLevel(logging.DEBUG)
2439
2440 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s- %(message)s")
2441
2442 stream_handler = logging.StreamHandler()
2443 stream_handler.setFormatter(formatter)
2444 logger.addHandler(stream_handler)
2445
2446 file_handler = logging.FileHandler("cpy.log")
2447 file_handler.setFormatter(formatter)
2448 logger.addHandler(file_handler)
2449
2450 # XDevAPI Protocol Example
2451 import logging
2452 import mysqlx
2453
2454 logger = logging.getLogger("mysqlx")
2455 logger.setLevel(logging.DEBUG)
2456
2457 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s- %(message)s")
2458
2459 stream_handler = logging.StreamHandler()
2460 stream_handler.setFormatter(formatter)
2461 logger.addHandler(stream_handler)
2462
2463 file_handler = logging.FileHandler("cpy.log")
2464 file_handler.setFormatter(formatter)
2465 logger.addHandler(file_handler)
2466 </pre></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-opentelemetry"></a>9.2 Telemetry Support</h2></div></div></div><p>
2467 MySQL Server added OpenTelemetry support in MySQL Enterprise Edition version 8.1.0,
2468 which is a <a class="ulink" href="https://www.mysql.com/products/enterprise/" target="_top">commercial
2469 product</a>. OpenTelemetry tracing support was added in Connector/Python
2470 8.1.0.
2471 </p><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-introduction"></a>Introduction to OpenTelemetry</h3></div></div></div><p>
2472 <span class="emphasis"><em>OpenTelemetry</em></span> is an observability framework
2473 and toolkit designed to create and manage telemetry data such as
2474 traces, metrics, and logs. Visit
2475 <a class="ulink" href="https://opentelemetry.io/docs/what-is-opentelemetry/" target="_top">What
2476 is OpenTelemetry?</a> for an explanation of what
2477 OpenTelemetry offers.
2478 </p><p>
2479 Connector/Python only supports tracing, so this guide does not include
2480 information about metric and log signals.
2481 </p></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-installation"></a>Installing Telemetry Support</h3></div></div></div><p>
2482 Install the OpenTelemetry API, SDK, and OTLP Exporter packages
2483 on the system along with Connector/Python. Optionally use the
2484 <code class="literal">[telemetry]</code> shortcut when installing the
2485 <code class="literal">mysql-connector-python</code> pip package to pull in
2486 specific OpenTelemetry versions as defined by the connector.
2487 </p><p>
2488 Manual installation:
2489 </p><pre data-lang="terminal" class="programlisting">pip install opentelemetry-api
2490 pip install opentelemetry-sdk
2491 pip install opentelemetry-exporter-otlp-proto-http
2492 pip install mysql-connector-python
2493 </pre><p>
2494 Or pass in [telemetry] when installing Connector/Python to perform the
2495 same actions except it installs a specific and tested
2496 OpenTelemetry version, which for Connector/Python 9.4.0 and later is
2497 OpenTelemetry v1.33.1:
2498 </p><pre data-lang="terminal" class="programlisting">pip install mysql-connector-python[telemetry]
2499 </pre><p>
2500 Connector/Python 8.1.0 through 8.4.0 included an [opentelemetry] option
2501 that installed a bundled version of the OpenTelemetry SDK/API
2502 libraries. Doing so in those versions was not recommended.
2503 </p></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-instrumentation"></a>Instrumentation</h3></div></div></div><p>
2504 For instrumenting an application, Connector/Python utilizes the official
2505 OpenTelemetry SDK to initialize OpenTelemetry, and the official
2506 OpenTelemetry API to instrument the application's code. This
2507 emits telemetry from the application and from utilized libraries
2508 that include instrumentation.
2509 </p><p>
2510 An application can be instrumented as demonstrated by this
2511 generic example:
2512 </p><pre data-lang="python" class="programlisting">from opentelemetry import trace
2513 from opentelemetry.sdk.trace import TracerProvider
2514 from opentelemetry.sdk.trace.export import BatchSpanProcessor
2515 from opentelemetry.sdk.trace.export import ConsoleSpanExporter
2516
2517 provider = TracerProvider()
2518 processor = BatchSpanProcessor(ConsoleSpanExporter())
2519 provider.add_span_processor(processor)
2520 trace.set_tracer_provider(provider)
2521 tracer = trace.get_tracer(__name__)
2522
2523 with tracer.start_as_current_span("app"):
2524 my_app()
2525 </pre><p>
2526 To better understand and get started using OpenTelemetry tracing
2527 for Python, see the official
2528 <a class="ulink" href="https://opentelemetry.io/docs/instrumentation/python/manual/" target="_top">OpenTelemetry
2529 Python Instrumentation</a> guide.
2530 </p></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-connector"></a>MySQL Connector/Python</h3></div></div></div><p>
2531 Connector/Python includes a MySQL instrumentor to instrument MySQL
2532 connections. This instrumentor provides an API and usage similar
2533 to OpenTelemetry's own MySQL package named
2534 <a class="ulink" href="https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-mysql" target="_top">opentelemetry-instrumentation-mysql</a>.
2535 </p><p>
2536 An exception is raised if a system does not support
2537 OpenTelemetry when attempting to use the instrumentor.
2538 </p><p>
2539 An example that utilizes the system's OpenTelemetry SDK/API and
2540 implements tracing with MySQL Connector/Python:
2541 </p><pre data-lang="python" class="programlisting">import os
2542 import mysql.connector
2543
2544 # An instrumentor that comes with mysql-connector-python
2545 from mysql.connector.opentelemetry.instrumentation import (
2546 MySQLInstrumentor as OracleMySQLInstrumentor,
2547 )
2548
2549 # Loading SDK from the system
2550 from opentelemetry import trace
2551 from opentelemetry.sdk.trace import TracerProvider
2552 from opentelemetry.sdk.trace.export import BatchSpanProcessor
2553 from opentelemetry.sdk.trace.export import ConsoleSpanExporter
2554
2555 provider = TracerProvider()
2556 processor = BatchSpanProcessor(ConsoleSpanExporter())
2557 provider.add_span_processor(processor)
2558 trace.set_tracer_provider(provider)
2559 tracer = trace.get_tracer(__name__)
2560
2561 config = {
2562 "host": "127.0.0.1",
2563 "user": "root",
2564 "password": os.environ.get("password"),
2565 "use_pure": True,
2566 "port": 3306,
2567 "database": "test",
2568 }
2569
2570 # Global instrumentation: all connection objects returned by
2571 # mysql.connector.connect will be instrumented.
2572 OracleMySQLInstrumentor().instrument()
2573
2574 with tracer.start_as_current_span("client_app"):
2575 with mysql.connector.connect(**config) as cnx:
2576 with cnx.cursor() as cur:
2577 cur.execute("SELECT @@version")
2578 _ = cur.fetchall()
2579 </pre></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-morphology"></a>Morphology of the Emitted Traces</h3></div></div></div><p>
2580 A trace generated by the Connector/Python instrumentor contains one
2581 connection span, and zero or more query spans as described in
2582 the rest of this section.
2583 </p><p>
2584 <span class="emphasis"><em>Connection Span</em></span>
2585 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
2586 Time from connection initialization to the moment the
2587 connection ends. The span is named
2588 <code class="literal">connection</code>.
2589 </p></li><li class="listitem"><p>
2590 If the application does not provide a span, the connection
2591 span generated is a ROOT span, originating in the connector.
2592 </p></li><li class="listitem"><p>
2593 If the application does provide a span, the query span
2594 generated is a CHILD span, originating in the connector.
2595 </p></li></ul></div><p>
2596 <span class="emphasis"><em>Query Span</em></span>
2597 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
2598 Time from when an SQL statement is requested (on the
2599 connector side) to the moment the connector finishes
2600 processing the server's reply to this statement.
2601 </p></li><li class="listitem"><p>
2602 A query span is created for each query request sent to the
2603 server. If the application does not provide a span, the
2604 query span generated is a ROOT span, originating in the
2605 connector.
2606 </p></li><li class="listitem"><p>
2607 If the application does provide a span, the query span
2608 generated is a CHILD span, originating in the connector.
2609 </p></li><li class="listitem"><p>
2610 The query span is linked to the existing connection span of
2611 the connection the query was executed.
2612 </p></li><li class="listitem"><p>
2613 Query attributes with prepared statements is supported as of
2614 MySQL Enterprise Edition 8.3.0.
2615 </p></li><li class="listitem"><p>
2616 Query spans for the connection object is supported as of
2617 Connector/Python 8.3.0, which includes methods such as commit(),
2618 rollback(), and cmd_change_user().
2619 </p></li></ul></div><p>
2620 <span class="emphasis"><em>Context Propagation</em></span>
2621 </p><p>
2622 By default, the trace context of the span in progress (if any)
2623 is propagated to the MySQL server.
2624 </p><p>
2625 Propagation has no effect when the MySQL server either disabled
2626 or does not support OpenTelemetry (the trace context is ignored
2627 by the server), however, when connecting to a server with
2628 OpenTelemetry enabled and configured, the server processes the
2629 propagated traces and creates parent-child relationships between
2630 the spans from the connector and those from the server. In other
2631 words, this provides trace continuity.
2632 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
2633 Context propagation with prepared statements is supported as
2634 of MySQL Enterprise Edition 8.3.0.
2635 </p></div><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
2636 The trace context is propagated for statements with query
2637 attributes defined in the MySQL client/server protocol, such
2638 as COM_QUERY.
2639 </p><p>
2640 The trace context is not propagated for statements without
2641 query attributes defined in the MySQL client/server
2642 protocol, statements such as COM_PING.
2643 </p></li><li class="listitem"><p>
2644 Trace context propagation is done via query attributes where
2645 a new attribute named "traceparent" is defined. Its value is
2646 based on the current span context. For details on how this
2647 value is computed, read the
2648 <a class="ulink" href="https://www.w3.org/TR/trace-context/#traceparent-header" target="_top">traceparent
2649 header W3C specification</a>.
2650 </p><p>
2651 If the "traceparent" query attribute is manually set for a
2652 query, then it is not be overwritten by the connector; it's
2653 assumed that it provides OTel context intended to forward to
2654 the server.
2655 </p></li></ul></div></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-disabling-trace"></a>Disabling Trace Context Propagation</h3></div></div></div><p>
2656 The boolean connection property named
2657 <code class="option">otel_context_propagation</code> is
2658 <code class="literal">True</code> by default. Setting it to
2659 <code class="literal">False</code> disables context propagation.
2660 </p><p>
2661 Since <code class="option">otel_context_propagation</code> is a connection
2662 property that can be changed after a connection is established
2663 (a connection object is created), setting such property to
2664 <code class="literal">False</code> does not have an effect over the spans
2665 generated during the connection phase. In other words, spans
2666 generated during the connection phase are always propagated
2667 since <code class="option">otel_context_propagation</code> is
2668 <code class="literal">True</code> by default.
2669 </p><p>
2670 This implementation is distinct from the implementation provided
2671 through the MySQL client library (or the related
2672 <code class="literal">telemetry_client</code> client-side plugin).
2673 </p></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-multi"></a>9.3 Executing Multiple Statements</h2></div></div></div><p>
2674 Connector/Python can execute either a single or multiple statements, this
2675 section references multiple statement and associated delimiter
2676 support.
2677 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
2678 Before Connector/Python 9.2.0, the <code class="option">multi</code> option was
2679 required to execute multiple statements. This option provided
2680 inconsistent results and was removed in 9.2.0.
2681 </p></div><p>
2682 Basic usage example:
2683 </p><pre data-lang="python" class="programlisting">sql_operation = """
2684 SET @a=1, @b='2024-02-01';
2685 SELECT @a, LENGTH('hello'), @b;
2686 SELECT @@version;
2687 """
2688
2689 with cnx.cursor() as cur:
2690 # Execute SQL; it can contain one or multiple statements
2691 cur.execute(sql_operation)
2692
2693 # Fetch result set, see other examples for additional information
2694 </pre><p>
2695 Custom delimiters are also supported (as of Connector/Python 9.2.0),
2696 including in scripts that include delimiters and multiple
2697 statements. The Sakila sample database file
2698 <code class="filename">sakila-schema.sql</code> is an example:
2699 </p><pre data-lang="python" class="programlisting">with cnx.cursor() as cur:
2700 with open(
2701 os.path.join("/path/to/files", "sakila-schema.sql"), encoding="utf-8"
2702 ) as code:
2703 cur.execute(code.read())
2704
2705 # Fetch result set, see other examples for additional information
2706 </pre><h3><a name="id3085"></a>Multiple Statement Result Mapping</h3><p>
2707 The optional <code class="literal">map_results</code> option (defaults to
2708 <code class="literal">False</code>) makes each statement relate to its
2709 corresponding result set.
2710 </p><pre data-lang="python" class="programlisting">sql_operation = ...
2711
2712 with cnx.cursor() as cur:
2713 # Execute SQL; it can contain one or multiple statements
2714 cur.execute(sql_operation, map_results=True)
2715
2716 # Fetch result set, see other examples for additional information
2717 </pre><p>
2718 A MySQL multi statement or script is composed of one or more
2719 single statements. There are two types of single statements:
2720 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
2721 <code class="literal">Simple</code>: these do not include a
2722 <code class="literal">BEGIN-END</code> body declaration.
2723 </p></li><li class="listitem"><p>
2724 <code class="literal">Compound</code>: these do include a
2725 <code class="literal">BEGIN-END</code> body declaration, such as:
2726 </p><pre data-lang="sql" class="programlisting">CREATE PROCEDURE dorepeat(p1 INT)
2727 BEGIN
2728 SET @x = 0;
2729 REPEAT SET @x = @x + 1; UNTIL @x &gt; p1 END REPEAT;
2730 END;
2731 </pre></li></ul></div><p>
2732 Connector/Python uses custom delimiters to break up a multi statement into
2733 individual statements when handling compound single statements,
2734 like how the MySQL client does. Simple single statements do not
2735 require custom delimiters but they can be used.
2736 </p><p>
2737 If no delimiters are utilized when working with compound single
2738 statements, the statement-result mapping may cause unexpected
2739 results. If mapping is disabled, compound single statements may or
2740 may not utilize delimiters.
2741 </p><p>
2742 An example using a mix of simple and compound statements:
2743 </p><pre data-lang="sql" class="programlisting">DROP PROCEDURE IF EXISTS dorepeat;
2744
2745 DELIMITER //
2746
2747 CREATE PROCEDURE dorepeat(p1 INT)
2748 BEGIN
2749 SET @x = 0;
2750 REPEAT SET @x = @x + 1; UNTIL @x &gt; p1 END REPEAT;
2751 END//
2752
2753 DELIMITER ;
2754
2755 SELECT @x;
2756 </pre><p>
2757 Connector/Python carries on a pre-processing step for handling delimiters
2758 that may affect performance for large scripts. There are also
2759 limitations when working with custom delimiters:
2760 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
2761 <code class="literal">Unsupported delimiters</code>: the following
2762 characters are not supported by the connector in
2763 <code class="literal">DELIMITER</code> statements:
2764 </p><pre data-lang="simple" class="programlisting">double quote: "
2765 single quote: '
2766 hash: #
2767 slash plus star: /*
2768 star plus slash: */
2769 </pre><p>
2770 Avoid using these symbols as part of a string representing a
2771 delimiter.
2772 </p></li><li class="listitem"><p>
2773 <code class="literal">DELIMITER</code>: the word DELIMITER and any of
2774 its lower and upper case combinations such as delimiter,
2775 DeLiMiter, and so on, are considered reserved words by the
2776 connector. Users must quote these when included in multi
2777 statements for other purposes different from declaring an
2778 actual statement delimiter; such as names for tables, columns,
2779 variables, in comments, and so on. Example:
2780 </p><pre data-lang="sql" class="programlisting">CREATE TABLE `delimiter` (begin INT, end INT); -- I am a `DELimiTer` comment
2781 </pre></li></ul></div><h3><a name="id3117"></a>Fetching Result Sets</h3><p>
2782 Basic usage (mapping disabled):
2783 </p><pre data-lang="python" class="programlisting">sql_operation = """
2784 SET @a=1, @b='2024-02-01';
2785 SELECT @a, LENGTH('hello'), @b;
2786 SELECT @@version;
2787 """
2788
2789 with cnx.cursor() as cur:
2790 # Execute a statement; it can be single or multi.
2791 cur.execute(sql_operation)
2792
2793 # Fetch result sets and do something with them
2794 result_set = cur.fetchall()
2795
2796 # do something with result set
2797 ...
2798
2799 while cur.nextset():
2800 result_set = cur.fetchall()
2801 # do something with result set
2802 ...
2803 </pre><p>
2804 The multi statement execution generates one or more result sets,
2805 in other words a set of result sets. The first result set is
2806 loadable after execution completes. You might fetch (using
2807 <code class="literal">fetchall()</code>) the current result set and process
2808 it, or not, and move onto the next one.
2809 </p><p>
2810 Alternatively, use the
2811 <a class="link" href="#connector-python-api-mysqlcursor-nextset" title="10.5.12 MySQLCursor.nextset() Method">nextset()</a>
2812 cursor API method to traverse a result set. This method makes the
2813 cursor skip to the next available set, discarding any remaining
2814 rows from the current set.
2815 </p><p>
2816 For executions generating only one result set, which happens when
2817 your script only includes one statement, the call to
2818 <a class="link" href="#connector-python-api-mysqlcursor-nextset" title="10.5.12 MySQLCursor.nextset() Method">nextset()</a>
2819 can be omitted as at most one result set is expected. Calling it
2820 returns <code class="literal">None</code> as there are no more sets.
2821 </p><p>
2822 With Statement-ResultSet mapping usage:
2823 </p><pre data-lang="python" class="programlisting">sql_operation = ...
2824
2825 with cnx.cursor() as cur:
2826 # Execute a statement; it can be single or multi.
2827 cur.execute(sql_operation, map_results=True)
2828
2829 # Fetch result sets and do something with them.
2830 # statement 1 is `SET @a=1, @b='2025-01-01'`,
2831 # result set from statement 1 is `[]` - aka, an empty set.
2832 result_set, statement = cur.fetchall(), cur.statement
2833 # do something with result set
2834 ...
2835
2836 # 1st call to `nextset()` will load the result set from statement 2,
2837 # statement 2 is `SELECT @a, LENGTH('hello'), @b`,
2838 # result set from statement 2 is `[(1, 5, '2025-01-01')]`.
2839 #
2840 # 2nd call to `nextset()` will load the result set from statement 3,
2841 # statement 3 is `SELECT @@version`,
2842 # result set from statement 3 is `[('9.2.0',)]`.
2843 #
2844 # 3rd call to `nextset()` will return `None` as there are no more sets,
2845 # leading to the end of the consumption process of result sets.
2846 while cur.nextset():
2847 result_set, statement = cur.fetchall(), cur.statement
2848 # do something with result set
2849 ...
2850 </pre><p>
2851 When the mapping is disabled
2852 (<code class="literal">map_results=False</code>), all result sets are
2853 related to the same statement, which is the one provided when
2854 calling <code class="literal">execute()</code>. In other words, the
2855 <code class="literal">statement</code> property does not change while result
2856 sets are consumed, which differs from when mapping is enabled,
2857 when the <code class="literal">statement</code> property returns the
2858 statement that caused the current result set. Therefore, the value
2859 of statement changes accordingly while the result sets are
2860 traversed.
2861 </p><h3><a name="id3134"></a>Shortcut for consuming result sets</h3><p>
2862 A fetch-related API command shortcut is available to consume
2863 result sets, this example is equivalent to the previously
2864 presented workflow.
2865 </p><pre data-lang="python" class="programlisting">sql_operation = '''
2866 SET @a=1, @b='2025-01-01';
2867 SELECT @a, LENGTH('hello'), @b;
2868 SELECT @@version;
2869 '''
2870 with cnx.cursor() as cur:
2871 cur.execute(sql_operation, map_results=True)
2872 for statement, result_set in cur.fetchsets():
2873 # do something with result set
2874 </pre><p>
2875 The
2876 <a class="link" href="#connector-python-api-mysqlcursor-fetchsets" title="10.5.13 MySQLCursor.fetchsets() Method">fetchsets()</a>
2877 method returns a generator where each item is a 2-tuple; the first
2878 element is the statement that caused the result set, and the
2879 second is the result set itself. If mapping is disabled, statement
2880 will not change as result sets are consumed.
2881 </p><p>
2882 If statement is not needed, then consider this simpler option:
2883 </p><pre data-lang="python" class="programlisting">sql_operation = ...
2884 with cnx.cursor() as cur:
2885 cur.execute(...)
2886 for _, result_set in cur.fetchsets():
2887 # do something with result set
2888 </pre></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-asyncio"></a>9.4 Asynchronous Connectivity</h2></div></div></div><p>
2889 Installing Connector/Python also installs the
2890 <code class="literal">mysql.connector.aio</code> package that integrates
2891 <a class="ulink" href="https://docs.python.org/3/library/asyncio.html" target="_top">asyncio</a>
2892 with the connector to allow integrating asynchronous MySQL
2893 interactions with an application.
2894 </p><p>
2895 Here are code examples that integrate
2896 <code class="literal">mysql.connector.aio</code> functionality:
2897 </p><h3><a name="id3148"></a>Basic Usage:</h3><pre data-lang="python" class="programlisting">from mysql.connector.aio import connect
2898
2899 # Connect to a MySQL server and get a cursor
2900 cnx = await connect(user="myuser", password="mypass")
2901 cur = await cnx.cursor()
2902
2903 # Execute a non-blocking query
2904 await cur.execute("SELECT version()")
2905
2906 # Retrieve the results of the query asynchronously
2907 results = await cur.fetchall()
2908 print(results)
2909
2910 # Close cursor and connection
2911 await cur.close()
2912 await cnx.close()
2913 </pre><h3><a name="id3150"></a>Usage with context managers:</h3><pre data-lang="python" class="programlisting">from mysql.connector.aio import connect
2914
2915 # Connect to a MySQL server and get a cursor
2916 async with await connect(user="myuser", password="mypass") as cnx:
2917 async with await cnx.cursor() as cur:
2918 # Execute a non-blocking query
2919 await cur.execute("SELECT version()")
2920
2921 # Retrieve the results of the query asynchronously
2922 results = await cur.fetchall()
2923 print(results)
2924 </pre><h3><a name="id3152"></a>Running Multiple Tasks Asynchronously</h3><p>
2925 This example showcases how to run tasks asynchronously and the
2926 usage of to_thread, which is the backbone to asynchronously run
2927 blocking functions:
2928 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
2929 The synchronous version of this example implements coroutines
2930 instead of following a common synchronous approach; this to
2931 explicitly demonstrate that only awaiting coroutines does not
2932 make the code run asynchronously. Functions included in the
2933 asyncio API must be used to achieve asynchronicity.
2934 </p></div><pre data-lang="python" class="programlisting">import asyncio
2935 import os
2936 import time
2937
2938 from mysql.connector.aio import connect
2939
2940 # Global variable which will help to format the job sequence output.
2941 # DISCLAIMER: this is an example for showcasing/demo purposes,
2942 # you should avoid global variables usage for production code.
2943 global indent
2944 indent = 0
2945
2946 # MySQL Connection arguments
2947 config = {
2948 "host": "127.0.0.1",
2949 "user": "root",
2950 "password": os.environ.get("MYPASS", ":("),
2951 "use_pure": True,
2952 "port": 3306,
2953 }
2954
2955
2956 async def job_sleep(n):
2957 """Take a nap for n seconds.
2958
2959 This job represents any generic task - it may be or not an IO task.
2960 """
2961 # Increment indent
2962 global indent
2963 offset = "\t" * indent
2964 indent += 1
2965
2966 # Emulating a generic job/task
2967 print(f"{offset}START_SLEEP")
2968 await asyncio.sleep(n)
2969 print(f"{offset}END_SLEEP")
2970
2971 return f"I slept for {n} seconds"
2972
2973
2974 async def job_mysql():
2975 """Connect to a MySQL Server and do some operations.
2976
2977 Run queries, run procedures, insert data, etc.
2978 """
2979 # Increment indent
2980 global indent
2981 offset = "\t" * indent
2982 indent += 1
2983
2984 # MySQL operations
2985 print(f"{offset}START_MYSQL_OPS")
2986 async with await connect(**config) as cnx:
2987 async with await cnx.cursor() as cur:
2988 await cur.execute("SELECT @@version")
2989 res = await cur.fetchone()
2990 time.sleep(1) # for simulating that the fetch isn't immediate
2991 print(f"{offset}END_MYSQL_OPS")
2992
2993 # return server version
2994 return res
2995
2996
2997 async def job_io():
2998 """Emulate an IO operation.
2999
3000 `to_thread` allows to run a blocking function asynchronously.
3001
3002 References:
3003 [asyncio.to_thread]: https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread
3004 """
3005
3006 # Emulating a native blocking IO procedure
3007 def io():
3008 """Blocking IO operation."""
3009 time.sleep(5)
3010
3011 # Increment indent
3012 global indent
3013 offset = "\t" * indent
3014 indent += 1
3015
3016 # Showcasing how a native blocking IO procedure can be awaited,
3017 print(f"{offset}START_IO")
3018 await asyncio.to_thread(io)
3019 print(f"{offset}END_IO")
3020
3021 return "I am an IO operation"
3022
3023
3024 async def main_asynchronous():
3025 """Running tasks asynchronously.
3026
3027 References:
3028 [asyncio.gather]: https://docs.python.org/3/library/asyncio-task.html#asyncio.gather
3029 """
3030 print("-------------------- ASYNCHRONOUS --------------------")
3031
3032 # reset indent
3033 global indent
3034 indent = 0
3035
3036 clock = time.time()
3037
3038 # `asyncio.gather()` allows to run awaitable objects
3039 # in the aws sequence asynchronously.\
3040
3041 # If all awaitables are completed successfully,
3042 # the result is an aggregate list of returned values.
3043 aws = (job_io(), job_mysql(), job_sleep(4))
3044 returned_vals = await asyncio.gather(*aws)
3045
3046 print(f"Elapsed time: {time.time() - clock:0.2f}")
3047
3048 # The order of result values corresponds to the
3049 # order of awaitables in aws.
3050 print(returned_vals, end="\n" * 2)
3051
3052 # Example expected output
3053 # -------------------- ASYNCHRONOUS --------------------
3054 # START_IO
3055 # START_MYSQL_OPS
3056 # START_SLEEP
3057 # END_MYSQL_OPS
3058 # END_SLEEP
3059 # END_IO
3060 # Elapsed time: 5.01
3061 # ['I am an IO operation', ('8.3.0-commercial',), 'I slept for 4 seconds']
3062
3063
3064 async def main_non_asynchronous():
3065 """Running tasks non-asynchronously"""
3066 print("------------------- NON-ASYNCHRONOUS -------------------")
3067
3068 # reset indent
3069 global indent
3070 indent = 0
3071
3072 clock = time.time()
3073
3074 # Sequence of awaitable objects
3075 aws = (job_io(), job_mysql(), job_sleep(4))
3076
3077 # The line below this docstring is the short version of:
3078 # coro1, coro2, coro3 = *aws
3079 # res1 = await coro1
3080 # res2 = await coro2
3081 # res3 = await coro3
3082 # returned_vals = [res1, res2, res3]
3083 # NOTE: Simply awaiting a coro does not make the code run asynchronously!
3084 returned_vals = [await coro for coro in aws] # this will run synchronously
3085
3086 print(f"Elapsed time: {time.time() - clock:0.2f}")
3087
3088 print(returned_vals, end="\n")
3089
3090 # Example expected output
3091 # ------------------- NON-ASYNCHRONOUS -------------------
3092 # START_IO
3093 # END_IO
3094 # START_MYSQL_OPS
3095 # END_MYSQL_OPS
3096 # START_SLEEP
3097 # END_SLEEP
3098 # Elapsed time: 10.07
3099 # ['I am an IO operation', ('8.3.0-commercial',), 'I slept for 4 seconds']
3100
3101
3102 if __name__ == "__main__":
3103 # `asyncio.run()`` allows to execute a coroutine (`coro`) and return the result.
3104 # You cannot run a coro without it.
3105
3106 # References:
3107 # [asyncio.run]: https://docs.python.org/3/library/asyncio-runner.html#asyncio.run
3108 assert asyncio.run(main_asynchronous()) == asyncio.run(main_non_asynchronous())
3109 </pre><p>
3110 It shows these three jobs running asynchronously:
3111 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
3112 <code class="literal">job_io</code>: Emulate an I/O operation; with
3113 to_thread to allow running a blocking function asynchronously.
3114 </p><p>
3115 Starts first, and takes five seconds to complete so is the
3116 last job to finish.
3117 </p></li><li class="listitem"><p>
3118 <code class="literal">job_mysql</code>: Connects to a MySQL server to
3119 perform operations such as queries and stored procedures.
3120 </p><p>
3121 Starts second, and takes one second to complete so is the
3122 first job to finish.
3123 </p></li><li class="listitem"><p>
3124 <code class="literal">job_sleep</code>: Sleeps for n seconds to
3125 represent a generic task.
3126 </p><p>
3127 Starts last, and takes four seconds to complete so is the
3128 second job to finish.
3129 </p></li></ul></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
3130 A lock/mutex wasn't added to the <code class="literal">indent</code>
3131 variable because multithreading isn't used; instead the unique
3132 active thread executes all of the jobs. Asynchronous execution
3133 is about completing other jobs while waiting for the result of
3134 an I/O operation.
3135 </p></div><h3><a name="id3174"></a>Asynchronous MySQL Queries</h3><p>
3136 This is a similar example that uses MySQL queries instead of
3137 generic jobs.
3138 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
3139 While cursors are not utilized in the these examples, the
3140 principles and workflow could apply to cursors by letting every
3141 connection object create a cursor to operate from.
3142 </p></div><p>
3143 Synchronous code to create and populate hundreds of tables:
3144 </p><pre data-lang="python" class="programlisting">import os
3145 import time
3146 from typing import TYPE_CHECKING, Callable, List, Tuple
3147
3148 from mysql.connector import connect
3149
3150 if TYPE_CHECKING:
3151 from mysql.connector.abstracts import (
3152 MySQLConnectionAbstract,
3153 )
3154
3155
3156 # MySQL Connection arguments
3157 config = {
3158 "host": "127.0.0.1",
3159 "user": "root",
3160 "password": os.environ.get("MYPASS", ":("),
3161 "use_pure": True,
3162 "port": 3306,
3163 }
3164
3165 exec_sequence = []
3166
3167
3168 def create_table(
3169 exec_seq: List[str], table_names: List[str], cnx: "MySQLConnectionAbstract", i: int
3170 ) -&gt; None:
3171 """Creates a table."""
3172 if i &gt;= len(table_names):
3173 return False
3174
3175 exec_seq.append(f"start_{i}")
3176 stmt = f"""
3177 CREATE TABLE IF NOT EXISTS {table_names[i]} (
3178 dish_id INT(11) UNSIGNED AUTO_INCREMENT UNIQUE KEY,
3179 category TEXT,
3180 dish_name TEXT,
3181 price FLOAT,
3182 servings INT,
3183 order_time TIME
3184 )
3185 """
3186 cnx.cmd_query(f"DROP TABLE IF EXISTS {table_names[i]}")
3187 cnx.cmd_query(stmt)
3188 exec_seq.append(f"end_{i}")
3189 return True
3190
3191
3192 def drop_table(
3193 exec_seq: List[str], table_names: List[str], cnx: "MySQLConnectionAbstract", i: int
3194 ) -&gt; None:
3195 """Drops a table."""
3196 if i &gt;= len(table_names):
3197 return False
3198
3199 exec_seq.append(f"start_{i}")
3200 cnx.cmd_query(f"DROP TABLE IF EXISTS {table_names[i]}")
3201 exec_seq.append(f"end_{i}")
3202 return True
3203
3204
3205 def main(
3206 kernel: Callable[[List[str], List[str], "MySQLConnectionAbstract", int], None],
3207 table_names: List[str],
3208 ) -&gt; Tuple[List, List]:
3209
3210 exec_seq = []
3211 database_name = "TABLE_CREATOR"
3212
3213 with connect(**config) as cnx:
3214 # Create/Setup database
3215 cnx.cmd_query(f"CREATE DATABASE IF NOT EXISTS {database_name}")
3216 cnx.cmd_query(f"USE {database_name}")
3217
3218 # Execute Kernel: Create or Delete tables
3219 for i in range(len(table_names)):
3220 kernel(exec_seq, table_names, cnx, i)
3221
3222 # Show tables
3223 cnx.cmd_query("SHOW tables")
3224 show_tables = cnx.get_rows()[0]
3225
3226 # Return execution sequence and table names retrieved with `SHOW tables;`.
3227 return exec_seq, show_tables
3228
3229
3230 if __name__ == "__main__":
3231 # with num_tables=511 -&gt; Elapsed time ~ 25.86
3232 clock = time.time()
3233 print_exec_seq = False
3234 num_tables = 511
3235 table_names = [f"table_sync_{n}" for n in range(num_tables)]
3236
3237 print("-------------------- SYNC CREATOR --------------------")
3238 exec_seq, show_tables = main(kernel=create_table, table_names=table_names)
3239 assert len(show_tables) == num_tables
3240 if print_exec_seq:
3241 print(exec_seq)
3242
3243 print("-------------------- SYNC DROPPER --------------------")
3244 exec_seq, show_tables = main(kernel=drop_table, table_names=table_names)
3245 assert len(show_tables) == 0
3246 if print_exec_seq:
3247 print(exec_seq)
3248
3249 print(f"Elapsed time: {time.time() - clock:0.2f}")
3250
3251 # Expected output with num_tables = 11:
3252 # -------------------- SYNC CREATOR --------------------
3253 # [
3254 # "start_0",
3255 # "end_0",
3256 # "start_1",
3257 # "end_1",
3258 # "start_2",
3259 # "end_2",
3260 # "start_3",
3261 # "end_3",
3262 # "start_4",
3263 # "end_4",
3264 # "start_5",
3265 # "end_5",
3266 # "start_6",
3267 # "end_6",
3268 # "start_7",
3269 # "end_7",
3270 # "start_8",
3271 # "end_8",
3272 # "start_9",
3273 # "end_9",
3274 # "start_10",
3275 # "end_10",
3276 # ]
3277 # -------------------- SYNC DROPPER --------------------
3278 # [
3279 # "start_0",
3280 # "end_0",
3281 # "start_1",
3282 # "end_1",
3283 # "start_2",
3284 # "end_2",
3285 # "start_3",
3286 # "end_3",
3287 # "start_4",
3288 # "end_4",
3289 # "start_5",
3290 # "end_5",
3291 # "start_6",
3292 # "end_6",
3293 # "start_7",
3294 # "end_7",
3295 # "start_8",
3296 # "end_8",
3297 # "start_9",
3298 # "end_9",
3299 # "start_10",
3300 # "end_10",
3301 # ]
3302 </pre><p>
3303 That script creates and deletes {num_tables} tables, and is fully
3304 sequential in that it creates and deletes table_{i} before moving
3305 to table_{i+1}.
3306 </p><p>
3307 An asynchronous code example for the same task:
3308 </p><pre class="programlisting">import asyncio
3309 import os
3310 import time
3311 from typing import TYPE_CHECKING, Callable, List, Tuple
3312
3313 from mysql.connector.aio import connect
3314
3315 if TYPE_CHECKING:
3316 from mysql.connector.aio.abstracts import (
3317 MySQLConnectionAbstract,
3318 )
3319
3320
3321 # MySQL Connection arguments
3322 config = {
3323 "host": "127.0.0.1",
3324 "user": "root",
3325 "password": os.environ.get("MYPASS", ":("),
3326 "use_pure": True,
3327 "port": 3306,
3328 }
3329
3330 exec_sequence = []
3331
3332
3333 async def create_table(
3334 exec_seq: List[str], table_names: List[str], cnx: "MySQLConnectionAbstract", i: int
3335 ) -&gt; None:
3336 """Creates a table."""
3337 if i &gt;= len(table_names):
3338 return False
3339
3340 exec_seq.append(f"start_{i}")
3341 stmt = f"""
3342 CREATE TABLE IF NOT EXISTS {table_names[i]} (
3343 dish_id INT(11) UNSIGNED AUTO_INCREMENT UNIQUE KEY,
3344 category TEXT,
3345 dish_name TEXT,
3346 price FLOAT,
3347 servings INT,
3348 order_time TIME
3349 )
3350 """
3351 await cnx.cmd_query(f"DROP TABLE IF EXISTS {table_names[i]}")
3352 await cnx.cmd_query(stmt)
3353 exec_seq.append(f"end_{i}")
3354 return True
3355
3356
3357 async def drop_table(
3358 exec_seq: List[str], table_names: List[str], cnx: "MySQLConnectionAbstract", i: int
3359 ) -&gt; None:
3360 """Drops a table."""
3361 if i &gt;= len(table_names):
3362 return False
3363
3364 exec_seq.append(f"start_{i}")
3365 await cnx.cmd_query(f"DROP TABLE IF EXISTS {table_names[i]}")
3366 exec_seq.append(f"end_{i}")
3367 return True
3368
3369
3370 async def main_async(
3371 kernel: Callable[[List[str], List[str], "MySQLConnectionAbstract", int], None],
3372 table_names: List[str],
3373 num_jobs: int = 2,
3374 ) -&gt; Tuple[List, List]:
3375 """The asynchronous tables creator...
3376 Reference:
3377 [as_completed]: https://docs.python.org/3/library/asyncio-task.html#asyncio.as_completed
3378 """
3379 exec_seq = []
3380 database_name = "TABLE_CREATOR"
3381
3382 # Create/Setup database
3383 # ---------------------
3384 # No asynchronous execution is done here.
3385 # NOTE: observe usage WITH context manager.
3386 async with await connect(**config) as cnx:
3387 await cnx.cmd_query(f"CREATE DATABASE IF NOT EXISTS {database_name}")
3388 await cnx.cmd_query(f"USE {database_name}")
3389 config["database"] = database_name
3390
3391 # Open connections
3392 # ----------------
3393 # `as_completed` allows to run awaitable objects in the `aws` iterable asynchronously.
3394 # NOTE: observe usage WITHOUT context manager.
3395 aws = [connect(**config) for _ in range(num_jobs)]
3396 cnxs: List["MySQLConnectionAbstract"] = [
3397 await coro for coro in asyncio.as_completed(aws)
3398 ]
3399
3400 # Execute Kernel: Create or Delete tables
3401 # -------------
3402 # N tables must be created/deleted and we can run up to `num_jobs` jobs asynchronously,
3403 # therefore we execute jobs in batches of size num_jobs`.
3404 returned_values, i = [True], 0
3405 while any(returned_values): # Keep running until i &gt;= len(table_names) for all jobs
3406 # Prepare coros: map connections/cursors and table-name IDs to jobs.
3407 aws = [
3408 kernel(exec_seq, table_names, cnx, i + idx) for idx, cnx in enumerate(cnxs)
3409 ]
3410 # When i &gt;= len(table_names) coro simply returns False, else True.
3411 returned_values = [await coro for coro in asyncio.as_completed(aws)]
3412 # Update table-name ID offset based on the number of jobs
3413 i += num_jobs
3414
3415 # Close cursors
3416 # -------------
3417 # `as_completed` allows to run awaitable objects in the `aws` iterable asynchronously.
3418 for coro in asyncio.as_completed([cnx.close() for cnx in cnxs]):
3419 await coro
3420
3421 # Load table names
3422 # ----------------
3423 # No asynchronous execution is done here.
3424 async with await connect(**config) as cnx:
3425 # Show tables
3426 await cnx.cmd_query("SHOW tables")
3427 show_tables = (await cnx.get_rows())[0]
3428
3429 # Return execution sequence and table names retrieved with `SHOW tables;`.
3430 return exec_seq, show_tables
3431
3432
3433 if __name__ == "__main__":
3434 # `asyncio.run()`` allows to execute a coroutine (`coro`) and return the result.
3435 # You cannot run a coro without it.
3436
3437 # References:
3438 # [asyncio.run]: https://docs.python.org/3/library/asyncio-runner.html#asyncio.run
3439
3440 # with num_tables=511 and num_jobs=3 -&gt; Elapsed time ~ 19.09
3441 # with num_tables=511 and num_jobs=12 -&gt; Elapsed time ~ 13.15
3442 clock = time.time()
3443 print_exec_seq = False
3444 num_tables = 511
3445 num_jobs = 12
3446 table_names = [f"table_async_{n}" for n in range(num_tables)]
3447
3448 print("-------------------- ASYNC CREATOR --------------------")
3449 exec_seq, show_tables = asyncio.run(
3450 main_async(kernel=create_table, table_names=table_names, num_jobs=num_jobs)
3451 )
3452 assert len(show_tables) == num_tables
3453 if print_exec_seq:
3454 print(exec_seq)
3455
3456 print("-------------------- ASYNC DROPPER --------------------")
3457 exec_seq, show_tables = asyncio.run(
3458 main_async(kernel=drop_table, table_names=table_names, num_jobs=num_jobs)
3459 )
3460 assert len(show_tables) == 0
3461 if print_exec_seq:
3462 print(exec_seq)
3463
3464 print(f"Elapsed time: {time.time() - clock:0.2f}")
3465
3466 # Expected output with num_tables = 11 and num_jobs = 3:
3467 # -------------------- ASYNC CREATOR --------------------
3468 # 11
3469 # [
3470 # "start_2",
3471 # "start_1",
3472 # "start_0",
3473 # "end_2",
3474 # "end_0",
3475 # "end_1",
3476 # "start_5",
3477 # "start_3",
3478 # "start_4",
3479 # "end_3",
3480 # "end_5",
3481 # "end_4",
3482 # "start_8",
3483 # "start_7",
3484 # "start_6",
3485 # "end_7",
3486 # "end_8",
3487 # "end_6",
3488 # "start_10",
3489 # "start_9",
3490 # "end_9",
3491 # "end_10",
3492 # ]
3493 # -------------------- ASYNC DROPPER --------------------
3494 # [
3495 # "start_1",
3496 # "start_2",
3497 # "start_0",
3498 # "end_1",
3499 # "end_2",
3500 # "end_0",
3501 # "start_3",
3502 # "start_5",
3503 # "start_4",
3504 # "end_4",
3505 # "end_5",
3506 # "end_3",
3507 # "start_6",
3508 # "start_8",
3509 # "start_7",
3510 # "end_7",
3511 # "end_6",
3512 # "end_8",
3513 # "start_10",
3514 # "start_9",
3515 # "end_9",
3516 # "end_10",
3517 # ]
3518 </pre><p>
3519 This output shows how the job flow isn't sequential in that up to
3520 {num_jobs} can be executed asynchronously. The jobs are run
3521 following a batch-like approach of {num_jobs} and waits until all
3522 terminate before launching the next batch, and the loop ends once
3523 no tables remain to create.
3524 </p><p>
3525 Performance comparison for these examples: the asynchronous
3526 implementation is about 26% faster when using 3 jobs, and 49%
3527 faster using 12 jobs. Note that increasing the number of jobs does
3528 add job management overhead which at some point evaporates the
3529 initial speed-up. The optimal number of jobs is problem-dependent,
3530 and is a value determined with experience.
3531 </p><p>
3532 As demonstrated, the asynchronous version requires more code to
3533 function than the non-asynchronous variant. Is it worth the
3534 effort? It depends on the goal as asynchronous code better
3535 optimizes performance, such as CPU usage, whereas writing standard
3536 synchronous code is simpler.
3537 </p><p>
3538 For additional information about the asyncio module, see the
3539 official
3540 <a class="ulink" href="https://docs.python.org/3/library/asyncio.html#module-asyncio" target="_top">Asynchronous
3541 I/O Python Documentation</a>.
3542 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-connection-pooling"></a>9.5 Connector/Python Connection Pooling</h2></div></div></div><p>
3543 Simple connection pooling is supported that has these
3544 characteristics:
3545 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
3546 The <code class="literal">mysql.connector.pooling</code> module
3547 implements pooling.
3548 </p></li><li class="listitem"><p>
3549 A pool opens a number of connections and handles thread safety
3550 when providing connections to requesters.
3551 </p></li><li class="listitem"><p>
3552 The size of a connection pool is configurable at pool creation
3553 time. It cannot be resized thereafter.
3554 </p></li><li class="listitem"><p>
3555 A connection pool can be named at pool creation time. If no
3556 name is given, one is generated using the connection
3557 parameters.
3558 </p></li><li class="listitem"><p>
3559 The connection pool name can be retrieved from the connection
3560 pool or connections obtained from it.
3561 </p></li><li class="listitem"><p>
3562 It is possible to have multiple connection pools. This enables
3563 applications to support pools of connections to different
3564 MySQL servers, for example.
3565 </p></li><li class="listitem"><p>
3566 For each connection request, the pool provides the next
3567 available connection. No round-robin or other scheduling
3568 algorithm is used. If a pool is exhausted, a
3569 <code class="literal">PoolError</code> is raised.
3570 </p></li><li class="listitem"><p>
3571 It is possible to reconfigure the connection parameters used
3572 by a pool. These apply to connections obtained from the pool
3573 thereafter. Reconfiguring individual connections obtained from
3574 the pool by calling the connection <code class="literal">config()</code>
3575 method is not supported.
3576 </p></li></ul></div><p>
3577 Applications that can benefit from connection-pooling capability
3578 include:
3579 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
3580 Middleware that maintains multiple connections to multiple
3581 MySQL servers and requires connections to be readily
3582 available.
3583 </p></li><li class="listitem"><p>
3584 websites that can have more <span class="quote">“<span class="quote">permanent</span>”</span>
3585 connections open to the MySQL server.
3586 </p></li></ul></div><p>
3587 A connection pool can be created implicitly or explicitly.
3588 </p><p>
3589 <span class="bold"><strong>To create a connection pool
3590 implicitly:</strong></span> Open a connection and specify one or more
3591 pool-related arguments (<code class="literal">pool_name</code>,
3592 <code class="literal">pool_size</code>). For example:
3593 </p><pre data-lang="python" class="programlisting">dbconfig = {
3594 "database": "test",
3595 "user": "joe"
3596 }
3597
3598 cnx = mysql.connector.connect(pool_name = "mypool",
3599 pool_size = 3,
3600 **dbconfig)
3601 </pre><p>
3602 The pool name is restricted to alphanumeric characters and the
3603 special characters <code class="literal">.</code>, <code class="literal">_</code>,
3604 <code class="literal">*</code>, <code class="literal">$</code>, and
3605 <code class="literal">#</code>. The pool name must be no more than
3606 <code class="literal">pooling.CNX_POOL_MAXNAMESIZE</code> characters long
3607 (default 64).
3608 </p><p>
3609 The pool size must be greater than 0 and less than or equal to
3610 <code class="literal">pooling.CNX_POOL_MAXSIZE</code> (default 32).
3611 </p><p>
3612 With either the <code class="literal">pool_name</code> or
3613 <code class="literal">pool_size</code> argument present, Connector/Python creates the
3614 new pool. If the <code class="literal">pool_name</code> argument is not
3615 given, the <code class="literal">connect()</code> call automatically
3616 generates the name, composed from whichever of the
3617 <code class="literal">host</code>, <code class="literal">port</code>,
3618 <code class="literal">user</code>, and <code class="literal">database</code>
3619 connection arguments are given, in that order. If the
3620 <code class="literal">pool_size</code> argument is not given, the default
3621 size is 5 connections.
3622 </p><p>
3623 Subsequent calls to <code class="literal">connect()</code> that name the
3624 same connection pool return connections from the existing pool.
3625 Any <code class="literal">pool_size</code> or connection parameter arguments
3626 are ignored, so the following <code class="literal">connect()</code> calls
3627 are equivalent to the original <code class="literal">connect()</code> call
3628 shown earlier:
3629 </p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(pool_name = "mypool", pool_size = 3)
3630 cnx = mysql.connector.connect(pool_name = "mypool", **dbconfig)
3631 cnx = mysql.connector.connect(pool_name = "mypool")
3632 </pre><p>
3633 Pooled connections obtained by calling
3634 <code class="literal">connect()</code> with a pool-related argument have a
3635 class of <code class="literal">PooledMySQLConnection</code> (see
3636 <a class="xref" href="#connector-python-api-pooledmysqlconnection" title="10.4 pooling.PooledMySQLConnection Class">Section 10.4, “pooling.PooledMySQLConnection Class”</a>).
3637 <code class="literal">PooledMySQLConnection</code> pooled connection objects
3638 are similar to <code class="literal">MySQLConnection</code> unpooled
3639 connection objects, with these differences:
3640 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
3641 To release a pooled connection obtained from a connection
3642 pool, invoke its <code class="literal">close()</code> method, just as
3643 for any unpooled connection. However, for a pooled connection,
3644 <code class="literal">close()</code> does not actually close the
3645 connection but returns it to the pool and makes it available
3646 for subsequent connection requests.
3647 </p></li><li class="listitem"><p>
3648 A pooled connection cannot be reconfigured using its
3649 <code class="literal">config()</code> method. Connection changes must be
3650 done through the pool object itself, as described shortly.
3651 </p></li><li class="listitem"><p>
3652 A pooled connection has a <code class="literal">pool_name</code>
3653 property that returns the pool name.
3654 </p></li></ul></div><p>
3655 <span class="bold"><strong>To create a connection pool
3656 explicitly:</strong></span> Create a
3657 <code class="literal">MySQLConnectionPool</code> object (see
3658 <a class="xref" href="#connector-python-api-mysqlconnectionpool" title="10.3 pooling.MySQLConnectionPool Class">Section 10.3, “pooling.MySQLConnectionPool Class”</a>):
3659 </p><pre data-lang="python" class="programlisting">dbconfig = {
3660 "database": "test",
3661 "user": "joe"
3662 }
3663
3664 cnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name = "mypool",
3665 pool_size = 3,
3666 **dbconfig)
3667 </pre><p>
3668 To request a connection from the pool, use its
3669 <code class="literal">get_connection()</code> method:
3670 </p><pre data-lang="python" class="programlisting">cnx1 = cnxpool.get_connection()
3671 cnx2 = cnxpool.get_connection()
3672 </pre><p>
3673 When you create a connection pool explicitly, it is possible to
3674 use the pool object's <code class="literal">set_config()</code> method to
3675 reconfigure the pool connection parameters:
3676 </p><pre data-lang="python" class="programlisting">dbconfig = {
3677 "database": "performance_schema",
3678 "user": "admin",
3679 "password": "<em class="replaceable"><code>password</code></em>"
3680 }
3681
3682 cnxpool.set_config(**dbconfig)
3683 </pre><p>
3684 Connections requested from the pool after the configuration change
3685 use the new parameters. Connections obtained before the change
3686 remain unaffected, but when they are closed (returned to the pool)
3687 are reopened with the new parameters before being returned by the
3688 pool for subsequent connection requests.
3689 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-django-backend"></a>9.6 Connector/Python Django Back End</h2></div></div></div><p>
3690 Connector/Python includes a <code class="literal">mysql.connector.django</code> module
3691 that provides a Django back end for MySQL. This back end supports
3692 new features found as of MySQL 5.6 such as fractional seconds
3693 support for temporal data types.
3694 </p><h3><a name="id3283"></a>Django Configuration</h3><p>
3695 Django uses a configuration file named
3696 <code class="filename">settings.py</code> that contains a variable called
3697 <code class="literal">DATABASES</code> (see
3698 <a class="ulink" href="https://docs.djangoproject.com/en/1.5/ref/settings/#std:setting-DATABASES" target="_top">https://docs.djangoproject.com/en/1.5/ref/settings/#std:setting-DATABASES</a>).
3699 To configure Django to use Connector/Python as the MySQL back end, the
3700 example found in the Django manual can be used as a basis:
3701 </p><pre data-lang="python" class="programlisting">DATABASES = {
3702 'default': {
3703 'NAME': 'user_data',
3704 'ENGINE': 'mysql.connector.django',
3705 'HOST': '127.0.0.1',
3706 'PORT': 3306,
3707 'USER': 'mysql_user',
3708 'PASSWORD': '<em class="replaceable"><code>password</code></em>',
3709 'OPTIONS': {
3710 'autocommit': True,
3711 'use_oure': True,
3712 'init_command': "SET foo='bar';"
3713 },
3714 }
3715 }
3716 </pre><p>
3717 It is possible to add more connection arguments using
3718 <code class="literal">OPTIONS</code>.
3719 </p><h3><a name="id3292"></a>Support for MySQL Features</h3><p>
3720 Django can launch the MySQL client application
3721 <span class="command"><strong>mysql</strong></span>. When the Connector/Python back end does this, it
3722 arranges for the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_sql_mode" target="_top"><code class="literal">sql_mode</code></a> system
3723 variable to be set to <code class="literal">TRADITIONAL</code> at startup.
3724 </p><p>
3725 Some MySQL features are enabled depending on the server version.
3726 For example, support for fractional seconds precision is enabled
3727 when connecting to a server from MySQL 5.6.4 or higher. Django's
3728 <code class="literal">DateTimeField</code> is stored in a MySQL column
3729 defined as <code class="literal">DATETIME(6)</code>, and
3730 <code class="literal">TimeField</code> is stored as
3731 <code class="literal">TIME(6)</code>. For more information about fractional
3732 seconds support, see <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html" target="_top">Fractional Seconds in Time Values</a>.
3733 </p><p>
3734 Using a custom class for data type conversation is supported as a
3735 subclass of
3736 <span class="emphasis"><em>mysql.connector.django.base.DjangoMySQLConverter</em></span>.
3737 This support was added in Connector/Python 8.0.29.
3738 </p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-reference"></a>Chapter 10 Connector/Python API Reference</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysql-connector">10.1 mysql.connector Module</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysql-connector-connect">10.1.1 mysql.connector.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-apilevel">10.1.2 mysql.connector.apilevel Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-paramstyle">10.1.3 mysql.connector.paramstyle Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-threadsafety">10.1.4 mysql.connector.threadsafety Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version">10.1.5 mysql.connector.__version__ Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version-info">10.1.6 mysql.connector.__version_info__ Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlconnection">10.2 connection.MySQLConnection Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlconnection-constructor">10.2.1 connection.MySQLConnection() Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-close">10.2.2 MySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-commit">10.2.3 MySQLConnection.commit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-config">10.2.4 MySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connect">10.2.5 MySQLConnection.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cursor">10.2.6 MySQLConnection.cursor() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-change-user">10.2.7 MySQLConnection.cmd_change_user() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-debug">10.2.8 MySQLConnection.cmd_debug() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-init-db">10.2.9 MySQLConnection.cmd_init_db() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-ping">10.2.10 MySQLConnection.cmd_ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-info">10.2.11 MySQLConnection.cmd_process_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-kill">10.2.12 MySQLConnection.cmd_process_kill() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query">10.2.13 MySQLConnection.cmd_query() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query-iter">10.2.14 MySQLConnection.cmd_query_iter() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-quit">10.2.15 MySQLConnection.cmd_quit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-refresh">10.2.16 MySQLConnection.cmd_refresh() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-reset-connection">10.2.17 MySQLConnection.cmd_reset_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-shutdown">10.2.18 MySQLConnection.cmd_shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-statistics">10.2.19 MySQLConnection.cmd_statistics() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-disconnect">10.2.20 MySQLConnection.disconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-row">10.2.21 MySQLConnection.get_row() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-rows">10.2.22 MySQLConnection.get_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-info">10.2.23 MySQLConnection.get_server_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-version">10.2.24 MySQLConnection.get_server_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-is-connected">10.2.25 MySQLConnection.is_connected() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-isset-client-flag">10.2.26 MySQLConnection.isset_client_flag() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-ping">10.2.27 MySQLConnection.ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reconnect">10.2.28 MySQLConnection.reconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reset-session">10.2.29 MySQLConnection.reset_session() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-rollback">10.2.30 MySQLConnection.rollback() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-charset-collation">10.2.31 MySQLConnection.set_charset_collation() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-client-flags">10.2.32 MySQLConnection.set_client_flags() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-shutdown">10.2.33 MySQLConnection.shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-start-transaction">10.2.34 MySQLConnection.start_transaction() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-autocommit">10.2.35 MySQLConnection.autocommit Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unread-results">10.2.36 MySQLConnection.unread_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-can-consume-results">10.2.37 MySQLConnection.can_consume_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-charset">10.2.38 MySQLConnection.charset Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-client-flags">10.2.39 MySQLConnection.client_flags Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-collation">10.2.40 MySQLConnection.collation Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connected">10.2.41 MySQLConnection.connected Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connection-id">10.2.42 MySQLConnection.connection_id Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-converter-class">10.2.43 MySQLConnection.converter-class Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-database">10.2.44 MySQLConnection.database Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-warnings">10.2.45 MySQLConnection.get_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-in-transaction">10.2.46 MySQLConnection.in_transaction Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-raise-on-warnings">10.2.47 MySQLConnection.raise_on_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-host">10.2.48 MySQLConnection.server_host Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-info">10.2.49 MySQLConnection.server_info Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-port">10.2.50 MySQLConnection.server_port Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-version">10.2.51 MySQLConnection.server_version Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-sql-mode">10.2.52 MySQLConnection.sql_mode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-time-zone">10.2.53 MySQLConnection.time_zone Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-use-unicode">10.2.54 MySQLConnection.use_unicode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unix-socket">10.2.55 MySQLConnection.unix_socket Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-user">10.2.56 MySQLConnection.user Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool">10.3 pooling.MySQLConnectionPool Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-constructor">10.3.1 pooling.MySQLConnectionPool Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-add-connection">10.3.2 MySQLConnectionPool.add_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-get-connection">10.3.3 MySQLConnectionPool.get_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-set-config">10.3.4 MySQLConnectionPool.set_config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-pool-name">10.3.5 MySQLConnectionPool.pool_name Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection">10.4 pooling.PooledMySQLConnection Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-constructor">10.4.1 pooling.PooledMySQLConnection Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-close">10.4.2 PooledMySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-config">10.4.3 PooledMySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-pool-name">10.4.4 PooledMySQLConnection.pool_name Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlcursor">10.5 cursor.MySQLCursor Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlcursor-constructor">10.5.1 cursor.MySQLCursor Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-add-attribute">10.5.2 MySQLCursor.add_attribute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-clear-attributes">10.5.3 MySQLCursor.clear_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-get-attributes">10.5.4 MySQLCursor.get_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-callproc">10.5.5 MySQLCursor.callproc() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-close">10.5.6 MySQLCursor.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-execute">10.5.7 MySQLCursor.execute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-executemany">10.5.8 MySQLCursor.executemany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchall">10.5.9 MySQLCursor.fetchall() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchmany">10.5.10 MySQLCursor.fetchmany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchone">10.5.11 MySQLCursor.fetchone() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-nextset">10.5.12 MySQLCursor.nextset() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchsets">10.5.13 MySQLCursor.fetchsets() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchwarnings">10.5.14 MySQLCursor.fetchwarnings() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-stored-results">10.5.15 MySQLCursor.stored_results() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-column-names">10.5.16 MySQLCursor.column_names Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-description">10.5.17 MySQLCursor.description Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-warnings">10.5.18 MySQLCursor.warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-lastrowid">10.5.19 MySQLCursor.lastrowid Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-rowcount">10.5.20 MySQLCursor.rowcount Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-statement">10.5.21 MySQLCursor.statement Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-with-rows">10.5.22 MySQLCursor.with_rows Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-cursor-subclasses">10.6 Subclasses cursor.MySQLCursor</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffered">10.6.1 cursor.MySQLCursorBuffered Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorraw">10.6.2 cursor.MySQLCursorRaw Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursordict">10.6.3 cursor.MySQLCursorDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffereddict">10.6.4 cursor.MySQLCursorBufferedDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorprepared">10.6.5 cursor.MySQLCursorPrepared Class</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-clientflag">10.7 constants.ClientFlag Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-fieldtype">10.8 constants.FieldType Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-sqlmode">10.9 constants.SQLMode Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-characterset">10.10 constants.CharacterSet Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-refreshoption">10.11 constants.RefreshOption Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors">10.12 Errors and Exceptions</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-errorcode">10.12.1 errorcode Module</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-error">10.12.2 errors.Error Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-dataerror">10.12.3 errors.DataError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-databaseerror">10.12.4 errors.DatabaseError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-integrityerror">10.12.5 errors.IntegrityError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-interfaceerror">10.12.6 errors.InterfaceError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-internalerror">10.12.7 errors.InternalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-notsupportederror">10.12.8 errors.NotSupportedError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-operationalerror">10.12.9 errors.OperationalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-poolerror">10.12.10 errors.PoolError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-programmingerror">10.12.11 errors.ProgrammingError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-warning">10.12.12 errors.Warning Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-custom-error-exception">10.12.13 errors.custom_error_exception() Function</a></span></dt></dl></dd></dl></div><p>
3739 This chapter contains the public API reference for Connector/Python. Examples
3740 should be considered working for Python 2.7, and Python 3.1 and
3741 greater. They might also work for older versions (such as Python
3742 2.4) unless they use features introduced in newer Python versions.
3743 For example, exception handling using the <code class="literal">as</code>
3744 keyword was introduced in Python 2.6 and will not work in Python
3745 2.4.
3746 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
3747 Python 2.7 support was removed in Connector/Python 8.0.24.
3748 </p></div><p>
3749 The following overview shows the <code class="literal">mysql.connector</code>
3750 package with its modules. Currently, only the most useful modules,
3751 classes, and methods for end users are documented.
3752 </p><pre data-lang="simple" class="programlisting">mysql.connector
3753 errorcode
3754 errors
3755 connection
3756 constants
3757 conversion
3758 cursor
3759 dbapi
3760 locales
3761 eng
3762 client_error
3763 protocol
3764 utils
3765 </pre><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-mysql-connector"></a>10.1 mysql.connector Module</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysql-connector-connect">10.1.1 mysql.connector.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-apilevel">10.1.2 mysql.connector.apilevel Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-paramstyle">10.1.3 mysql.connector.paramstyle Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-threadsafety">10.1.4 mysql.connector.threadsafety Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version">10.1.5 mysql.connector.__version__ Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version-info">10.1.6 mysql.connector.__version_info__ Property</a></span></dt></dl></div><a class="indexterm" name="id3316"></a><a class="indexterm" name="id3318"></a><p>
3766 The <code class="literal">mysql.connector</code> module provides top-level
3767 methods and properties.
3768 </p><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-connect"></a>10.1.1 mysql.connector.connect() Method</h3></div></div></div><a class="indexterm" name="id3324"></a><a class="indexterm" name="id3326"></a><p>
3769 This method sets up a connection, establishing a session with
3770 the MySQL server. If no arguments are given, it uses the already
3771 configured or default values. For a complete list of possible
3772 arguments, see <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
3773 </p><p>
3774 A connection with the MySQL server can be established using
3775 either the <code class="literal">mysql.connector.connect()</code> method
3776 or the <code class="literal">mysql.connector.MySQLConnection()</code>
3777 class:
3778 </p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(user='joe', database='test')
3779 cnx = MySQLConnection(user='joe', database='test')
3780 </pre><p>
3781 For descriptions of connection methods and properties, see
3782 <a class="xref" href="#connector-python-api-mysqlconnection" title="10.2 connection.MySQLConnection Class">Section 10.2, “connection.MySQLConnection Class”</a>.
3783 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-apilevel"></a>10.1.2 mysql.connector.apilevel Property</h3></div></div></div><a class="indexterm" name="id3338"></a><a class="indexterm" name="id3340"></a><p>
3784 This property is a string that indicates the supported DB API
3785 level.
3786 </p><pre data-lang="python" class="programlisting">
3787 &gt;&gt;&gt; mysql.connector.apilevel
3788 '2.0'</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-paramstyle"></a>10.1.3 mysql.connector.paramstyle Property</h3></div></div></div><a class="indexterm" name="id3346"></a><a class="indexterm" name="id3348"></a><p>
3789 This property is a string that indicates the Connector/Python default
3790 parameter style.
3791 </p><pre data-lang="python" class="programlisting">
3792 &gt;&gt;&gt; mysql.connector.paramstyle
3793 'pyformat'</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-threadsafety"></a>10.1.4 mysql.connector.threadsafety Property</h3></div></div></div><a class="indexterm" name="id3354"></a><a class="indexterm" name="id3356"></a><p>
3794 This property is an integer that indicates the supported level
3795 of thread safety provided by Connector/Python.
3796 </p><pre data-lang="python" class="programlisting">
3797 &gt;&gt;&gt; mysql.connector.threadsafety
3798 1</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-version"></a>10.1.5 mysql.connector.__version__ Property</h3></div></div></div><a class="indexterm" name="id3362"></a><a class="indexterm" name="id3364"></a><p>
3799 This property indicates the Connector/Python version as a string. It is
3800 available as of Connector/Python 1.1.0.
3801 </p><pre data-lang="python" class="programlisting">
3802 &gt;&gt;&gt; mysql.connector.__version__
3803 '1.1.0'</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-version-info"></a>10.1.6 mysql.connector.__version_info__ Property</h3></div></div></div><a class="indexterm" name="id3370"></a><a class="indexterm" name="id3372"></a><p>
3804 This property indicates the Connector/Python version as an array of version
3805 components. It is available as of Connector/Python 1.1.0.
3806 </p><pre data-lang="python" class="programlisting">
3807 &gt;&gt;&gt; mysql.connector.__version_info__
3808 (1, 1, 0, 'a', 0)</pre></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-mysqlconnection"></a>10.2 connection.MySQLConnection Class</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysqlconnection-constructor">10.2.1 connection.MySQLConnection() Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-close">10.2.2 MySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-commit">10.2.3 MySQLConnection.commit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-config">10.2.4 MySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connect">10.2.5 MySQLConnection.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cursor">10.2.6 MySQLConnection.cursor() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-change-user">10.2.7 MySQLConnection.cmd_change_user() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-debug">10.2.8 MySQLConnection.cmd_debug() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-init-db">10.2.9 MySQLConnection.cmd_init_db() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-ping">10.2.10 MySQLConnection.cmd_ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-info">10.2.11 MySQLConnection.cmd_process_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-kill">10.2.12 MySQLConnection.cmd_process_kill() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query">10.2.13 MySQLConnection.cmd_query() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query-iter">10.2.14 MySQLConnection.cmd_query_iter() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-quit">10.2.15 MySQLConnection.cmd_quit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-refresh">10.2.16 MySQLConnection.cmd_refresh() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-reset-connection">10.2.17 MySQLConnection.cmd_reset_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-shutdown">10.2.18 MySQLConnection.cmd_shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-statistics">10.2.19 MySQLConnection.cmd_statistics() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-disconnect">10.2.20 MySQLConnection.disconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-row">10.2.21 MySQLConnection.get_row() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-rows">10.2.22 MySQLConnection.get_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-info">10.2.23 MySQLConnection.get_server_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-version">10.2.24 MySQLConnection.get_server_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-is-connected">10.2.25 MySQLConnection.is_connected() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-isset-client-flag">10.2.26 MySQLConnection.isset_client_flag() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-ping">10.2.27 MySQLConnection.ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reconnect">10.2.28 MySQLConnection.reconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reset-session">10.2.29 MySQLConnection.reset_session() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-rollback">10.2.30 MySQLConnection.rollback() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-charset-collation">10.2.31 MySQLConnection.set_charset_collation() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-client-flags">10.2.32 MySQLConnection.set_client_flags() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-shutdown">10.2.33 MySQLConnection.shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-start-transaction">10.2.34 MySQLConnection.start_transaction() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-autocommit">10.2.35 MySQLConnection.autocommit Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unread-results">10.2.36 MySQLConnection.unread_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-can-consume-results">10.2.37 MySQLConnection.can_consume_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-charset">10.2.38 MySQLConnection.charset Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-client-flags">10.2.39 MySQLConnection.client_flags Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-collation">10.2.40 MySQLConnection.collation Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connected">10.2.41 MySQLConnection.connected Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connection-id">10.2.42 MySQLConnection.connection_id Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-converter-class">10.2.43 MySQLConnection.converter-class Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-database">10.2.44 MySQLConnection.database Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-warnings">10.2.45 MySQLConnection.get_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-in-transaction">10.2.46 MySQLConnection.in_transaction Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-raise-on-warnings">10.2.47 MySQLConnection.raise_on_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-host">10.2.48 MySQLConnection.server_host Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-info">10.2.49 MySQLConnection.server_info Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-port">10.2.50 MySQLConnection.server_port Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-version">10.2.51 MySQLConnection.server_version Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-sql-mode">10.2.52 MySQLConnection.sql_mode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-time-zone">10.2.53 MySQLConnection.time_zone Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-use-unicode">10.2.54 MySQLConnection.use_unicode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unix-socket">10.2.55 MySQLConnection.unix_socket Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-user">10.2.56 MySQLConnection.user Property</a></span></dt></dl></div><a class="indexterm" name="id3378"></a><a class="indexterm" name="id3380"></a><p>
3809 The <code class="literal">MySQLConnection</code> class is used to open and
3810 manage a connection to a MySQL server. It also used to send
3811 commands and SQL statements and read the results.
3812 </p><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-constructor"></a>10.2.1 connection.MySQLConnection() Constructor</h3></div></div></div><a class="indexterm" name="id3386"></a><a class="indexterm" name="id3388"></a><p>
3813 Syntax:
3814 </p><pre data-lang="python" class="programlisting">cnx = MySQLConnection(**kwargs)
3815 </pre><p>
3816 The <code class="literal">MySQLConnection</code> constructor initializes
3817 the attributes and when at least one argument is passed, it
3818 tries to connect to the MySQL server.
3819 </p><p>
3820 For a complete list of arguments, see
3821 <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
3822 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-close"></a>10.2.2 MySQLConnection.close() Method</h3></div></div></div><a class="indexterm" name="id3398"></a><a class="indexterm" name="id3400"></a><p>
3823 Syntax:
3824 </p><pre data-lang="python" class="programlisting">cnx.close()
3825 </pre><p>
3826 <code class="literal">close()</code> is a synonym for
3827 <code class="literal">disconnect()</code>. See
3828 <a class="xref" href="#connector-python-api-mysqlconnection-disconnect" title="10.2.20 MySQLConnection.disconnect() Method">Section 10.2.20, “MySQLConnection.disconnect() Method”</a>.
3829 </p><p>
3830 For a connection obtained from a connection pool,
3831 <code class="literal">close()</code> does not actually close it but
3832 returns it to the pool and makes it available for subsequent
3833 connection requests. See
3834 <a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>.
3835 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-commit"></a>10.2.3 MySQLConnection.commit() Method</h3></div></div></div><a class="indexterm" name="id3413"></a><a class="indexterm" name="id3415"></a><p>
3836 This method sends a <code class="literal">COMMIT</code> statement to the
3837 MySQL server, committing the current transaction. Since by
3838 default Connector/Python does not autocommit, it is important to call this
3839 method after every transaction that modifies data for tables
3840 that use transactional storage engines.
3841 </p><pre data-lang="python" class="programlisting">
3842 &gt;&gt;&gt; cursor.execute("INSERT INTO employees (first_name) VALUES (%s), (%s)", ('Jane', 'Mary'))
3843 &gt;&gt;&gt; cnx.commit()</pre><p>
3844 To roll back instead and discard modifications, see the
3845 <a class="link" href="#connector-python-api-mysqlconnection-rollback" title="10.2.30 MySQLConnection.rollback() Method">rollback()</a>
3846 method.
3847 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-config"></a>10.2.4 MySQLConnection.config() Method</h3></div></div></div><a class="indexterm" name="id3424"></a><a class="indexterm" name="id3426"></a><p>
3848 Syntax:
3849 </p><pre data-lang="python" class="programlisting">cnx.config(**kwargs)
3850 </pre><p>
3851 Configures a <code class="literal">MySQLConnection</code> instance after
3852 it has been instantiated. For a complete list of possible
3853 arguments, see <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
3854 </p><p>
3855 Arguments:
3856 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
3857 <code class="literal">kwargs</code>: Connection arguments.
3858 </p></li></ul></div><p>
3859 You could use the <code class="literal">config()</code> method to change
3860 (for example) the user name, then call
3861 <code class="literal">reconnect()</code>.
3862 </p><p>
3863 Example:
3864 </p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(user='joe', database='test')
3865 # Connected as 'joe'
3866 cnx.config(user='jane')
3867 cnx.reconnect()
3868 # Now connected as 'jane'
3869 </pre><p>
3870 For a connection obtained from a connection pool,
3871 <code class="literal">config()</code> raises an exception. See
3872 <a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>.
3873 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-connect"></a>10.2.5 MySQLConnection.connect() Method</h3></div></div></div><a class="indexterm" name="id3448"></a><a class="indexterm" name="id3450"></a><p>
3874 Syntax:
3875 </p><pre data-lang="python" class="programlisting">MySQLConnection.connect(**kwargs)
3876 </pre><p>
3877 This method sets up a connection, establishing a session with
3878 the MySQL server. If no arguments are given, it uses the already
3879 configured or default values. For a complete list of possible
3880 arguments, see <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
3881 </p><p>
3882 Arguments:
3883 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
3884 <code class="literal">kwargs</code>: Connection arguments.
3885 </p></li></ul></div><p>
3886 Example:
3887 </p><pre data-lang="python" class="programlisting">cnx = MySQLConnection(user='joe', database='test')
3888 </pre><p>
3889 For a connection obtained from a conection pool, the connection
3890 object class is <code class="literal">PooledMySQLConnection</code>. A
3891 pooled connection differs from an unpooled connection as
3892 described in
3893 <a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>.
3894 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cursor"></a>10.2.6 MySQLConnection.cursor() Method</h3></div></div></div><a class="indexterm" name="id3468"></a><a class="indexterm" name="id3470"></a><p>
3895 Syntax:
3896 </p><pre data-lang="python" class="programlisting">cursor = cnx.cursor([arg=value[, arg=value]...])
3897 </pre><p>
3898 This method returns a <code class="literal">MySQLCursor()</code> object,
3899 or a subclass of it depending on the passed arguments. The
3900 returned object is a <code class="literal">cursor.CursorBase</code>
3901 instance. For more information about cursor objects, see
3902 <a class="xref" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">Section 10.5, “cursor.MySQLCursor Class”</a>, and
3903 <a class="xref" href="#connector-python-api-cursor-subclasses" title="10.6 Subclasses cursor.MySQLCursor">Section 10.6, “Subclasses cursor.MySQLCursor”</a>.
3904 </p><p>
3905 Arguments may be passed to the <code class="literal">cursor()</code>
3906 method to control what type of cursor to create:
3907 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
3908 If <code class="literal">buffered</code> is <code class="literal">True</code>,
3909 the cursor fetches all rows from the server after an
3910 operation is executed. This is useful when queries return
3911 small result sets. <code class="literal">buffered</code> can be used
3912 alone, or in combination with the
3913 <code class="literal">dictionary</code> argument.
3914 </p><p>
3915 <code class="literal">buffered</code> can also be passed to
3916 <a class="link" href="#connector-python-api-mysql-connector-connect" title="10.1.1 mysql.connector.connect() Method"><code class="literal">connect()</code></a>
3917 to set the default buffering mode for all cursors created
3918 from the connection object. See
3919 <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
3920 </p><p>
3921 For information about the implications of buffering, see
3922 <a class="xref" href="#connector-python-api-mysqlcursorbuffered" title="10.6.1 cursor.MySQLCursorBuffered Class">Section 10.6.1, “cursor.MySQLCursorBuffered Class”</a>.
3923 </p></li><li class="listitem"><p>
3924 If <code class="literal">raw</code> is <code class="literal">True</code>, the
3925 cursor skips the conversion from MySQL data types to Python
3926 types when fetching rows. A raw cursor is usually used to
3927 get better performance or when you want to do the conversion
3928 yourself.
3929 </p><p>
3930 <code class="literal">raw</code> can also be passed to
3931 <a class="link" href="#connector-python-api-mysql-connector-connect" title="10.1.1 mysql.connector.connect() Method"><code class="literal">connect()</code></a>
3932 to set the default raw mode for all cursors created from the
3933 connection object. See
3934 <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
3935 </p></li><li class="listitem"><p>
3936 If <code class="literal">dictionary</code> is <code class="literal">True</code>,
3937 the cursor returns rows as dictionaries. This argument is
3938 available as of Connector/Python 2.0.0.
3939 </p></li><li class="listitem"><p>
3940 If <code class="literal">prepared</code> is <code class="literal">True</code>,
3941 the cursor is used for executing prepared statements. This
3942 argument is available as of Connector/Python 1.1.2. The C extension
3943 supports this as of Connector/Python 8.0.17.
3944 </p></li><li class="listitem"><p>
3945 The <code class="literal">cursor_class</code> argument can be used to
3946 pass a class to use for instantiating a new cursor. It must
3947 be a subclass of <code class="literal">cursor.CursorBase</code>.
3948 </p></li></ul></div><p>
3949 The returned object depends on the combination of the arguments.
3950 Examples:
3951 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
3952 If not buffered and not raw: <code class="literal">MySQLCursor</code>
3953 </p></li><li class="listitem"><p>
3954 If buffered and not raw:
3955 <code class="literal">MySQLCursorBuffered</code>
3956 </p></li><li class="listitem"><p>
3957 If not buffered and raw: <code class="literal">MySQLCursorRaw</code>
3958 </p></li><li class="listitem"><p>
3959 If buffered and raw:
3960 <code class="literal">MySQLCursorBufferedRaw</code>
3961 </p></li></ul></div></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-change-user"></a>10.2.7 MySQLConnection.cmd_change_user() Method</h3></div></div></div><a class="indexterm" name="id3532"></a><a class="indexterm" name="id3534"></a><p>
3962 Changes the user using <code class="literal">username</code> and
3963 <code class="literal">password</code>. It also causes the specified
3964 <code class="literal">database</code> to become the default (current)
3965 database. It is also possible to change the character set using
3966 the <code class="literal">charset</code> argument.
3967 </p><p>
3968 Syntax:
3969 </p><pre data-lang="python" class="programlisting">cnx.cmd_change_user(username='', password='', database='', charset=33)
3970 </pre><p>
3971 Returns a dictionary containing the OK packet information.
3972 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-debug"></a>10.2.8 MySQLConnection.cmd_debug() Method</h3></div></div></div><a class="indexterm" name="id3546"></a><a class="indexterm" name="id3548"></a><p>
3973 Instructs the server to write debugging information to the error
3974 log. The connected user must have the
3975 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html#priv_super" target="_top"><code class="literal">SUPER</code></a> privilege.
3976 </p><p>
3977 Returns a dictionary containing the OK packet information.
3978 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-init-db"></a>10.2.9 MySQLConnection.cmd_init_db() Method</h3></div></div></div><a class="indexterm" name="id3556"></a><a class="indexterm" name="id3558"></a><p>
3979 Syntax:
3980 </p><pre data-lang="python" class="programlisting">cnx.cmd_init_db(db_name)
3981 </pre><p>
3982 This method makes specified database the default (current)
3983 database. In subsequent queries, this database is the default
3984 for table references that include no explicit database
3985 qualifier.
3986 </p><p>
3987 Returns a dictionary containing the OK packet information.
3988 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-ping"></a>10.2.10 MySQLConnection.cmd_ping() Method</h3></div></div></div><a class="indexterm" name="id3566"></a><a class="indexterm" name="id3568"></a><p>
3989 Checks whether the connection to the server is working.
3990 </p><p>
3991 This method is not to be used directly. Use
3992 <a class="link" href="#connector-python-api-mysqlconnection-ping" title="10.2.27 MySQLConnection.ping() Method">ping()</a>
3993 or
3994 <a class="link" href="#connector-python-api-mysqlconnection-is-connected" title="10.2.25 MySQLConnection.is_connected() Method">is_connected()</a>
3995 instead.
3996 </p><p>
3997 Returns a dictionary containing the OK packet information.
3998 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-process-info"></a>10.2.11 MySQLConnection.cmd_process_info() Method</h3></div></div></div><a class="indexterm" name="id3577"></a><a class="indexterm" name="id3579"></a><p>
3999 This method raises the NotSupportedError exception. Instead, use
4000 the <code class="literal">SHOW PROCESSLIST</code> statement or query the
4001 tables found in the database
4002 <code class="literal">INFORMATION_SCHEMA</code>.
4003 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
4004 This MySQL Server functionality is deprecated.
4005 </p></div></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-process-kill"></a>10.2.12 MySQLConnection.cmd_process_kill() Method</h3></div></div></div><a class="indexterm" name="id3589"></a><a class="indexterm" name="id3591"></a><p>
4006 Syntax:
4007 </p><pre data-lang="python" class="programlisting">cnx.cmd_process_kill(mysql_pid)
4008 </pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
4009 This MySQL Server functionality is deprecated.
4010 </p></div><p>
4011 Asks the server to kill the thread specified by
4012 <code class="literal">mysql_pid</code>. Although still available, it is
4013 better to use the <code class="literal">KILL</code> SQL statement.
4014 </p><p>
4015 Returns a dictionary containing the OK packet information.
4016 </p><p>
4017 The following two lines have the same effect:
4018 </p><pre data-lang="python" class="programlisting">
4019 &gt;&gt;&gt; cnx.cmd_process_kill(123)
4020 &gt;&gt;&gt; cnx.cmd_query('KILL 123')</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-query"></a>10.2.13 MySQLConnection.cmd_query() Method</h3></div></div></div><a class="indexterm" name="id3606"></a><a class="indexterm" name="id3608"></a><p>
4021 Syntax:
4022 </p><pre data-lang="python" class="programlisting">cnx.cmd_query(statement)
4023 </pre><p>
4024 This method sends the given <code class="literal">statement</code> to the
4025 MySQL server and returns a result. To send multiple statements,
4026 use the
4027 <a class="link" href="#connector-python-api-mysqlconnection-cmd-query-iter" title="10.2.14 MySQLConnection.cmd_query_iter() Method">cmd_query_iter()</a>
4028 method instead.
4029 </p><p>
4030 The returned dictionary contains information depending on what
4031 kind of query was executed. If the query is a
4032 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a> statement, the result
4033 contains information about columns. Other statements return a
4034 dictionary containing OK or EOF packet information.
4035 </p><p>
4036 Errors received from the MySQL server are raised as exceptions.
4037 An <code class="literal">InterfaceError</code> is raised when multiple
4038 results are found.
4039 </p><p>
4040 Returns a dictionary.
4041 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-query-iter"></a>10.2.14 MySQLConnection.cmd_query_iter() Method</h3></div></div></div><a class="indexterm" name="id3623"></a><a class="indexterm" name="id3625"></a><p>
4042 Syntax:
4043 </p><pre data-lang="python" class="programlisting">cnx.cmd_query_iter(statement)
4044 </pre><p>
4045 Similar to the
4046 <a class="link" href="#connector-python-api-mysqlconnection-cmd-query" title="10.2.13 MySQLConnection.cmd_query() Method">cmd_query()</a>
4047 method, but returns a generator object to iterate through
4048 results. Use <code class="literal">cmd_query_iter()</code> when sending
4049 multiple statements, and separate the statements with
4050 semicolons.
4051 </p><p>
4052 The following example shows how to iterate through the results
4053 after sending multiple statements:
4054 </p><pre data-lang="python" class="programlisting">statement = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
4055 for result in cnx.cmd_query_iter(statement):
4056 if 'columns' in result:
4057 columns = result['columns']
4058 rows = cnx.get_rows()
4059 else:
4060 # do something useful with INSERT result
4061 </pre><p>
4062 Returns a generator object.
4063 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-quit"></a>10.2.15 MySQLConnection.cmd_quit() Method</h3></div></div></div><a class="indexterm" name="id3637"></a><a class="indexterm" name="id3639"></a><p>
4064 This method sends a <code class="literal">QUIT</code> command to the MySQL
4065 server, closing the current connection. Since there is no
4066 response from the MySQL server, the packet that was sent is
4067 returned.
4068 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-refresh"></a>10.2.16 MySQLConnection.cmd_refresh() Method</h3></div></div></div><a class="indexterm" name="id3645"></a><a class="indexterm" name="id3647"></a><p>
4069 Syntax:
4070 </p><pre data-lang="python" class="programlisting">cnx.cmd_refresh(options)
4071 </pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
4072 This MySQL Server functionality is deprecated.
4073 </p></div><p>
4074 This method flushes tables or caches, or resets replication
4075 server information. The connected user must have the
4076 <code class="literal">RELOAD</code> privilege.
4077 </p><p>
4078 The <code class="literal">options</code> argument should be a bitmask
4079 value constructed using constants from the
4080 <code class="literal">constants.RefreshOption</code> class.
4081 </p><p>
4082 For a list of options, see
4083 <a class="xref" href="#connector-python-api-refreshoption" title="10.11 constants.RefreshOption Class">Section 10.11, “constants.RefreshOption Class”</a>.
4084 </p><p>
4085 Example:
4086 </p><pre data-lang="python" class="programlisting">
4087 &gt;&gt;&gt; from mysql.connector import RefreshOption
4088 &gt;&gt;&gt; refresh = RefreshOption.LOG | RefreshOption.THREADS
4089 &gt;&gt;&gt; cnx.cmd_refresh(refresh)</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-reset-connection"></a>10.2.17 MySQLConnection.cmd_reset_connection() Method</h3></div></div></div><a class="indexterm" name="id3665"></a><a class="indexterm" name="id3667"></a><p>
4090 Syntax:
4091 </p><pre data-lang="python" class="programlisting">cnx.cmd_reset_connection()
4092 </pre><p>
4093 Resets the connection by sending a
4094 <code class="literal">COM_RESET_CONNECTION</code> command to the server to
4095 clear the session state.
4096 </p><p>
4097 This method permits the session state to be cleared without
4098 reauthenticating. For MySQL servers older than 5.7.3 (when
4099 <code class="literal">COM_RESET_CONNECTION</code> was introduced), the
4100 <a class="link" href="#connector-python-api-mysqlconnection-reset-session" title="10.2.29 MySQLConnection.reset_session() Method"><code class="literal">reset_session()</code></a>
4101 method can be used instead. That method resets the session state
4102 by reauthenticating, which is more expensive.
4103 </p><p>
4104 This method was added in Connector/Python 1.2.1.
4105 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-shutdown"></a>10.2.18 MySQLConnection.cmd_shutdown() Method</h3></div></div></div><a class="indexterm" name="id3680"></a><a class="indexterm" name="id3682"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
4106 This MySQL Server functionality is deprecated.
4107 </p></div><p>
4108 Asks the database server to shut down. The connected user must
4109 have the <code class="literal">SHUTDOWN</code> privilege.
4110 </p><p>
4111 Returns a dictionary containing the OK packet information.
4112 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-statistics"></a>10.2.19 MySQLConnection.cmd_statistics() Method</h3></div></div></div><a class="indexterm" name="id3692"></a><a class="indexterm" name="id3694"></a><p>
4113 Returns a dictionary containing information about the MySQL
4114 server including uptime in seconds and the number of running
4115 threads, questions, reloads, and open tables.
4116 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-disconnect"></a>10.2.20 MySQLConnection.disconnect() Method</h3></div></div></div><a class="indexterm" name="id3699"></a><a class="indexterm" name="id3701"></a><p>
4117 This method tries to send a <code class="literal">QUIT</code> command and
4118 close the socket. It raises no exceptions.
4119 </p><p>
4120 <code class="literal">MySQLConnection.close()</code> is a synonymous
4121 method name and more commonly used.
4122 </p><p>
4123 To shut down the connection without sending a
4124 <code class="literal">QUIT</code> command first, use
4125 <a class="link" href="#connector-python-api-mysqlconnection-shutdown" title="10.2.33 MySQLConnection.shutdown() Method"><code class="literal">shutdown()</code></a>.
4126 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-get-row"></a>10.2.21 MySQLConnection.get_row() Method</h3></div></div></div><a class="indexterm" name="id3713"></a><a class="indexterm" name="id3715"></a><p>
4127 This method retrieves the next row of a query result set,
4128 returning a tuple.
4129 </p><p>
4130 The tuple returned by <code class="literal">get_row()</code> consists of:
4131 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
4132 The row as a tuple containing byte objects, or
4133 <code class="literal">None</code> when no more rows are available.
4134 </p></li><li class="listitem"><p>
4135 EOF packet information as a dictionary containing
4136 <code class="literal">status_flag</code> and
4137 <code class="literal">warning_count</code>, or <code class="literal">None</code>
4138 when the row returned is not the last row.
4139 </p></li></ul></div><p>
4140 The <code class="literal">get_row()</code> method is used by
4141 <a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">MySQLCursor</a>
4142 to fetch rows.
4143 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-get-rows"></a>10.2.22 MySQLConnection.get_rows() Method</h3></div></div></div><a class="indexterm" name="id3734"></a><a class="indexterm" name="id3736"></a><p>
4144 Syntax:
4145 </p><pre data-lang="python" class="programlisting">cnx.get_rows(count=None)
4146 </pre><p>
4147 This method retrieves all or remaining rows of a query result
4148 set, returning a tuple containing the rows as sequences and the
4149 EOF packet information. The count argument can be used to obtain
4150 a given number of rows. If count is not specified or is
4151 <code class="literal">None</code>, all rows are retrieved.
4152 </p><p>
4153 The tuple returned by <code class="literal">get_rows()</code> consists of:
4154 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
4155 A list of tuples containing the row data as byte objects, or
4156 an empty list when no rows are available.
4157 </p></li><li class="listitem"><p>
4158 EOF packet information as a dictionary containing
4159 <code class="literal">status_flag</code> and
4160 <code class="literal">warning_count</code>.
4161 </p></li></ul></div><p>
4162 An <code class="literal">InterfaceError</code> is raised when all rows
4163 have been retrieved.
4164 </p><p>
4165 <a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">MySQLCursor</a>
4166 uses the <code class="literal">get_rows()</code> method to fetch rows.
4167 </p><p>
4168 Returns a tuple.
4169 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-get-server-info"></a>10.2.23 MySQLConnection.get_server_info() Method</h3></div></div></div><a class="indexterm" name="id3759"></a><a class="indexterm" name="id3761"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
4170 This method has been deprecated as of 9.3.0. Use the property
4171 method
4172 <a class="xref" href="#connector-python-api-mysqlconnection-server-info" title="10.2.49 MySQLConnection.server_info Property">Section 10.2.49, “MySQLConnection.server_info Property”</a>
4173 instead.
4174 </p></div><p>
4175 This method returns the MySQL server information verbatim as a
4176 string, for example <code class="literal">'5.6.11-log'</code>, or
4177 <code class="literal">None</code> when not connected.
4178 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-get-server-version"></a>10.2.24 MySQLConnection.get_server_version() Method</h3></div></div></div><a class="indexterm" name="id3772"></a><a class="indexterm" name="id3774"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
4179 This method has been deprecated as of 9.3.0. Use the property
4180 method
4181 <a class="xref" href="#connector-python-api-mysqlconnection-server-version" title="10.2.51 MySQLConnection.server_version Property">Section 10.2.51, “MySQLConnection.server_version Property”</a>
4182 instead.
4183 </p></div><p>
4184 This method returns the MySQL server version as a tuple, or
4185 <code class="literal">None</code> when not connected.
4186 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-is-connected"></a>10.2.25 MySQLConnection.is_connected() Method</h3></div></div></div><a class="indexterm" name="id3784"></a><a class="indexterm" name="id3786"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
4187 This method has been deprecated as of 9.3.0. Use the property
4188 method
4189 <a class="xref" href="#connector-python-api-mysqlconnection-connected" title="10.2.41 MySQLConnection.connected Property">Section 10.2.41, “MySQLConnection.connected Property”</a>
4190 instead.
4191 </p></div><p>
4192 Reports whether the connection to MySQL Server is available.
4193 </p><p>
4194 This method checks whether the connection to MySQL is available
4195 using the
4196 <a class="link" href="#connector-python-api-mysqlconnection-ping" title="10.2.27 MySQLConnection.ping() Method">ping()</a>
4197 method, but unlike <code class="literal">ping()</code>,
4198 <code class="literal">is_connected()</code> returns
4199 <code class="literal">True</code> when the connection is available,
4200 <code class="literal">False</code> otherwise.
4201 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-isset-client-flag"></a>10.2.26 MySQLConnection.isset_client_flag() Method</h3></div></div></div><a class="indexterm" name="id3801"></a><a class="indexterm" name="id3803"></a><p>
4202 Syntax:
4203 </p><pre data-lang="python" class="programlisting">cnx.isset_client_flag(flag)
4204 </pre><p>
4205 This method returns <code class="literal">True</code> if the client flag
4206 was set, <code class="literal">False</code> otherwise.
4207 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-ping"></a>10.2.27 MySQLConnection.ping() Method</h3></div></div></div><a class="indexterm" name="id3812"></a><a class="indexterm" name="id3814"></a><p>
4208 Syntax:
4209 </p><pre data-lang="python" class="programlisting">cnx.ping(reconnect=False, attempts=1, delay=0)
4210 </pre><p>
4211 Check whether the connection to the MySQL server is still
4212 available.
4213 </p><p>
4214 When <code class="literal">reconnect</code> is set to
4215 <code class="literal">True</code>, one or more <code class="literal">attempts</code>
4216 are made to try to reconnect to the MySQL server, and these
4217 options are forwarded to the
4218 <a class="link" href="#connector-python-api-mysqlconnection-reconnect" title="10.2.28 MySQLConnection.reconnect() Method">reconnect()</a>&gt;method.
4219 Use the <code class="literal">delay</code> argument (seconds) if you want
4220 to wait between each retry.
4221 </p><p>
4222 When the connection is not available, an
4223 <code class="literal">InterfaceError</code> is raised. Use the
4224 <a class="link" href="#connector-python-api-mysqlconnection-is-connected" title="10.2.25 MySQLConnection.is_connected() Method">is_connected()</a>
4225 method to check the connection without raising an error.
4226 </p><p>
4227 Raises <code class="literal">InterfaceError</code> on errors.
4228 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-reconnect"></a>10.2.28 MySQLConnection.reconnect() Method</h3></div></div></div><a class="indexterm" name="id3832"></a><a class="indexterm" name="id3834"></a><p>
4229 Syntax:
4230 </p><pre data-lang="python" class="programlisting">cnx.reconnect(attempts=1, delay=0)
4231 </pre><p>
4232 Attempt to reconnect to the MySQL server.
4233 </p><p>
4234 The argument <code class="literal">attempts</code> specifies the number of
4235 times a reconnect is tried. The <code class="literal">delay</code>
4236 argument is the number of seconds to wait between each retry.
4237 </p><p>
4238 You might set the number of attempts higher and use a longer
4239 delay when you expect the MySQL server to be down for
4240 maintenance, or when you expect the network to be temporarily
4241 unavailable.
4242 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-reset-session"></a>10.2.29 MySQLConnection.reset_session() Method</h3></div></div></div><a class="indexterm" name="id3845"></a><a class="indexterm" name="id3847"></a><p>
4243 Syntax:
4244 </p><pre data-lang="python" class="programlisting">cnx.reset_session(user_variables = None, session_variables = None)
4245 </pre><p>
4246 Resets the connection by reauthenticating to clear the session
4247 state. <code class="literal">user_variables</code>, if given, is a
4248 dictionary of user variable names and values.
4249 <code class="literal">session_variables</code>, if given, is a dictionary
4250 of system variable names and values. The method sets each
4251 variable to the given value.
4252 </p><p>
4253 Example:
4254 </p><pre data-lang="python" class="programlisting">user_variables = {'var1': '1', 'var2': '10'}
4255 session_variables = {'wait_timeout': 100000, 'sql_mode': 'TRADITIONAL'}
4256 self.cnx.reset_session(user_variables, session_variables)
4257 </pre><p>
4258 This method resets the session state by reauthenticating. For
4259 MySQL servers 5.7 or higher, the
4260 <a class="link" href="#connector-python-api-mysqlconnection-cmd-reset-connection" title="10.2.17 MySQLConnection.cmd_reset_connection() Method"><code class="literal">cmd_reset_connection()</code></a>
4261 method is a more lightweight alternative.
4262 </p><p>
4263 This method was added in Connector/Python 1.2.1.
4264 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-rollback"></a>10.2.30 MySQLConnection.rollback() Method</h3></div></div></div><a class="indexterm" name="id3862"></a><a class="indexterm" name="id3864"></a><p>
4265 This method sends a <code class="literal">ROLLBACK</code> statement to the
4266 MySQL server, undoing all data changes from the current
4267 transaction. By default, Connector/Python does not autocommit, so it is
4268 possible to cancel transactions when using transactional storage
4269 engines such as <code class="literal">InnoDB</code>.
4270 </p><pre data-lang="python" class="programlisting">
4271 &gt;&gt;&gt; cursor.execute("INSERT INTO employees (first_name) VALUES (%s), (%s)", ('Jane', 'Mary'))
4272 &gt;&gt;&gt; cnx.rollback()</pre><p>
4273 To <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_commit" target="_top">commit</a> modifications, see
4274 the
4275 <a class="link" href="#connector-python-api-mysqlconnection-commit" title="10.2.3 MySQLConnection.commit() Method">commit()</a>
4276 method.
4277 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-set-charset-collation"></a>10.2.31 MySQLConnection.set_charset_collation() Method</h3></div></div></div><a class="indexterm" name="id3875"></a><a class="indexterm" name="id3877"></a><p>
4278 Syntax:
4279 </p><pre data-lang="python" class="programlisting">cnx.set_charset_collation(charset=None, collation=None)
4280 </pre><p>
4281 This method sets the character set and collation to be used for
4282 the current connection. The <code class="literal">charset</code> argument
4283 can be either the name of a character set, or the numerical
4284 equivalent as defined in
4285 <code class="literal">constants.CharacterSet</code>.
4286 </p><p>
4287 When <code class="literal">collation</code> is <code class="literal">None</code>,
4288 the default collation for the character set is used.
4289 </p><p>
4290 In the following example, we set the character set to
4291 <code class="literal">latin1</code> and the collation to
4292 <code class="literal">latin1_swedish_ci</code> (the default collation for:
4293 <code class="literal">latin1</code>):
4294 </p><pre data-lang="python" class="programlisting">
4295 &gt;&gt;&gt; cnx = mysql.connector.connect(user='scott')
4296 &gt;&gt;&gt; cnx.set_charset_collation('latin1')</pre><p>
4297 Specify a given collation as follows:
4298 </p><pre data-lang="python" class="programlisting">
4299 &gt;&gt;&gt; cnx = mysql.connector.connect(user='scott')
4300 &gt;&gt;&gt; cnx.set_charset_collation('latin1', 'latin1_general_ci')</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-set-client-flags"></a>10.2.32 MySQLConnection.set_client_flags() Method</h3></div></div></div><a class="indexterm" name="id3896"></a><a class="indexterm" name="id3898"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
4301 This method has been deprecated as of 9.3.0. Use the property
4302 method
4303 <a class="xref" href="#connector-python-api-mysqlconnection-client-flags" title="10.2.39 MySQLConnection.client_flags Property">Section 10.2.39, “MySQLConnection.client_flags Property”</a>
4304 instead.
4305 </p></div><p>
4306 Syntax:
4307 </p><pre data-lang="python" class="programlisting">cnx.set_client_flags(flags)
4308 </pre><p>
4309 This method sets the client flags to use when connecting to the
4310 MySQL server, and returns the new value as an integer. The
4311 <code class="literal">flags</code> argument can be either an integer or a
4312 sequence of valid client flag values (see
4313 <a class="xref" href="#connector-python-api-clientflag" title="10.7 constants.ClientFlag Class">Section 10.7, “constants.ClientFlag Class”</a>).
4314 </p><p>
4315 If <code class="literal">flags</code> is a sequence, each item in the
4316 sequence sets the flag when the value is positive or unsets it
4317 when negative. For example, to unset
4318 <code class="literal">LONG_FLAG</code> and set the
4319 <code class="literal">FOUND_ROWS</code> flags:
4320 </p><pre data-lang="python" class="programlisting">
4321 &gt;&gt;&gt; from mysql.connector.constants import ClientFlag
4322 &gt;&gt;&gt; cnx.set_client_flags([ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG])
4323 &gt;&gt;&gt; cnx.reconnect()</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
4324 Client flags are only set or used when connecting to the MySQL
4325 server. It is therefore necessary to reconnect after making
4326 changes.
4327 </p></div></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-shutdown"></a>10.2.33 MySQLConnection.shutdown() Method</h3></div></div></div><a class="indexterm" name="id3918"></a><a class="indexterm" name="id3920"></a><p>
4328 This method closes the socket. It raises no exceptions.
4329 </p><p>
4330 Unlike
4331 <a class="link" href="#connector-python-api-mysqlconnection-disconnect" title="10.2.20 MySQLConnection.disconnect() Method"><code class="literal">disconnect()</code></a>,
4332 <code class="literal">shutdown()</code> closes the client connection
4333 without attempting to send a <code class="literal">QUIT</code> command to
4334 the server first. Thus, it will not block if the connection is
4335 disrupted for some reason such as network failure.
4336 </p><p>
4337 <code class="literal">shutdown()</code> was added in Connector/Python 2.0.1.
4338 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-start-transaction"></a>10.2.34 MySQLConnection.start_transaction() Method</h3></div></div></div><a class="indexterm" name="id3932"></a><a class="indexterm" name="id3934"></a><p>
4339 This method starts a transaction. It accepts arguments
4340 indicating whether to use a consistent snapshot, which
4341 transaction isolation level to use, and the transaction access
4342 mode:
4343 </p><pre data-lang="python" class="programlisting">cnx.start_transaction(consistent_snapshot=<em class="replaceable"><code>bool</code></em>,
4344 isolation_level=<em class="replaceable"><code>level</code></em>,
4345 readonly=<em class="replaceable"><code>access_mode</code></em>)
4346 </pre><p>
4347 The default <code class="literal">consistent_snapshot</code> value is
4348 <code class="literal">False</code>. If the value is
4349 <code class="literal">True</code>, Connector/Python sends <code class="literal">WITH CONSISTENT
4350 SNAPSHOT</code> with the statement. MySQL ignores this for
4351 isolation levels for which that option does not apply.
4352 </p><p>
4353 The default <code class="literal">isolation_level</code> value is
4354 <code class="literal">None</code>, and permitted values are <code class="literal">'READ
4355 UNCOMMITTED'</code>, <code class="literal">'READ COMMITTED'</code>,
4356 <code class="literal">'REPEATABLE READ'</code>, and
4357 <code class="literal">'SERIALIZABLE'</code>. If the
4358 <code class="literal">isolation_level</code> value is
4359 <code class="literal">None</code>, no isolation level is sent, so the
4360 default level applies.
4361 </p><p>
4362 The <code class="literal">readonly</code> argument can be
4363 <code class="literal">True</code> to start the transaction in
4364 <code class="literal">READ ONLY</code> mode or <code class="literal">False</code> to
4365 start it in <code class="literal">READ WRITE</code> mode. If
4366 <code class="literal">readonly</code> is omitted, the server's default
4367 access mode is used. For details about transaction access mode,
4368 see the description for the <code class="literal">START TRANSACTION</code>
4369 statement at <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/commit.html" target="_top">START TRANSACTION, COMMIT, and ROLLBACK Statements</a>. If the server is older
4370 than MySQL 5.6.5, it does not support setting the access mode
4371 and Connector/Python raises a <code class="literal">ValueError</code>.
4372 </p><p>
4373 Invoking <code class="literal">start_transaction()</code> raises a
4374 <code class="literal">ProgrammingError</code> if invoked while a
4375 transaction is currently in progress. This differs from
4376 executing a <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/commit.html" target="_top"><code class="literal">START
4377 TRANSACTION</code></a> SQL statement while a transaction is in
4378 progress; the statement implicitly commits the current
4379 transaction.
4380 </p><p>
4381 To determine whether a transaction is active for the connection,
4382 use the
4383 <a class="link" href="#connector-python-api-mysqlconnection-in-transaction" title="10.2.46 MySQLConnection.in_transaction Property">in_transaction</a>
4384 property.
4385 </p><p>
4386 <code class="literal">start_transaction()</code> was added in MySQL Connector/Python
4387 1.1.0. The <code class="literal">readonly</code> argument was added in
4388 Connector/Python 1.1.5.
4389 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-autocommit"></a>10.2.35 MySQLConnection.autocommit Property</h3></div></div></div><a class="indexterm" name="id3977"></a><a class="indexterm" name="id3979"></a><p>
4390 This property can be assigned a value of <code class="literal">True</code>
4391 or <code class="literal">False</code> to enable or disable the autocommit
4392 feature of MySQL. The property can be invoked to retrieve the
4393 current autocommit setting.
4394 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
4395 Autocommit is disabled by default when connecting through
4396 Connector/Python. This can be enabled using the
4397 <code class="literal">autocommit</code>
4398 <a class="link" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">connection
4399 parameter</a>.
4400 </p></div><p>
4401 When the autocommit is turned off, you must
4402 <a class="link" href="#connector-python-api-mysqlconnection-commit" title="10.2.3 MySQLConnection.commit() Method">commit</a>
4403 transactions when using transactional storage engines such as
4404 <code class="literal">InnoDB</code> or <code class="literal">NDBCluster</code>.
4405 </p><pre data-lang="python" class="programlisting">
4406 &gt;&gt;&gt; cnx.autocommit
4407 False
4408 &gt;&gt;&gt; cnx.autocommit = True
4409 &gt;&gt;&gt; cnx.autocommit
4410 True</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-unread-results"></a>10.2.36 MySQLConnection.unread_results Property</h3></div></div></div><a class="indexterm" name="id3995"></a><a class="indexterm" name="id3997"></a><p>
4411 Indicates whether there is an unread result. It is set to
4412 <code class="literal">False</code> if there is not an unread result,
4413 otherwise <code class="literal">True</code>. This is used by cursors to
4414 check whether another cursor still needs to retrieve its result
4415 set.
4416 </p><p>
4417 Do not set the value of this property, as only the connector
4418 should change the value. In other words, treat this as a
4419 read-only property.
4420 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-can-consume-results"></a>10.2.37 MySQLConnection.can_consume_results Property</h3></div></div></div><a class="indexterm" name="id4005"></a><a class="indexterm" name="id4007"></a><p>
4421 This property indicates the value of the
4422 <code class="literal">consume_results</code> connection parameter that
4423 controls whether result sets produced by queries are
4424 automatically read and discarded. See
4425 <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
4426 </p><p>
4427 This method was added in Connector/Python 2.1.1.
4428 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-charset"></a>10.2.38 MySQLConnection.charset Property</h3></div></div></div><a class="indexterm" name="id4015"></a><a class="indexterm" name="id4017"></a><p>
4429 This property returns a string indicating which character set is
4430 used for the connection, whether or not it is connected.
4431 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-client-flags"></a>10.2.39 MySQLConnection.client_flags Property</h3></div></div></div><a class="indexterm" name="id4022"></a><a class="indexterm" name="id4024"></a><p>
4432 Syntax:
4433 </p><pre data-lang="python" class="programlisting">&gt;&gt;&gt; cnx.client_flags=flags
4434 &gt;&gt;&gt; cnx.clieng_flags
4435 </pre><p>
4436 This property sets the client flags to use when connecting to
4437 the MySQL server, and returns the set value as an integer. The
4438 <code class="literal">flags</code> value can be either an integer or a
4439 sequence of valid client flag values (see
4440 <a class="xref" href="#connector-python-api-clientflag" title="10.7 constants.ClientFlag Class">Section 10.7, “constants.ClientFlag Class”</a>).
4441 </p><p>
4442 If <code class="literal">flags</code> is a sequence, each item in the
4443 sequence sets the flag when the value is positive or unsets it
4444 when negative. For example, to unset
4445 <code class="literal">LONG_FLAG</code> and set the
4446 <code class="literal">FOUND_ROWS</code> flags:
4447 </p><pre data-lang="python" class="programlisting">
4448 &gt;&gt;&gt; from mysql.connector.constants import ClientFlag
4449 &gt;&gt;&gt; cnx.client_flags=[ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG]
4450 &gt;&gt;&gt; cnx.reconnect()</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
4451 Client flags are only set or used when connecting to the MySQL
4452 server. It is therefore necessary to reconnect after making
4453 changes.
4454 </p></div></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-collation"></a>10.2.40 MySQLConnection.collation Property</h3></div></div></div><a class="indexterm" name="id4040"></a><a class="indexterm" name="id4042"></a><p>
4455 This property returns a string indicating which collation is
4456 used for the connection, whether or not it is connected.
4457 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-connected"></a>10.2.41 MySQLConnection.connected Property</h3></div></div></div><a class="indexterm" name="id4047"></a><a class="indexterm" name="id4049"></a><p>
4458 Reports whether the connection to MySQL Server is available.
4459 </p><p>
4460 This read-only property checks whether the connection to MySQL
4461 is available using the
4462 <a class="link" href="#connector-python-api-mysqlconnection-ping" title="10.2.27 MySQLConnection.ping() Method">ping()</a>
4463 method; but unlike <code class="literal">ping()</code>,
4464 <code class="literal">connected</code> returns <code class="literal">True</code>
4465 when the connection is available, and <code class="literal">False</code>
4466 otherwise.
4467 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-connection-id"></a>10.2.42 MySQLConnection.connection_id Property</h3></div></div></div><a class="indexterm" name="id4060"></a><a class="indexterm" name="id4062"></a><p>
4468 This property returns the integer connection ID (thread ID or
4469 session ID) for the current connection or
4470 <code class="literal">None</code> when not connected.
4471 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-converter-class"></a>10.2.43 MySQLConnection.converter-class Property</h3></div></div></div><a class="indexterm" name="id4068"></a><a class="indexterm" name="id4070"></a><p>
4472 This property sets and returns the converter class to use when
4473 configuring the connection.
4474 </p><pre data-lang="python" class="programlisting"># get the current converter class being used
4475 print(cnx.converter_class)
4476 &gt;&gt; &lt;class 'mysql.connector.conversion.MySQLConverter'&gt;
4477
4478 class TestConverter(MySQLConverterBase): ...
4479
4480 # set the custom converter class
4481 cnx.converter_class = TestConverter
4482 print(cnx.converter_class)
4483 &gt;&gt; &lt;class '__main__.TestConverter'&gt;</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-database"></a>10.2.44 MySQLConnection.database Property</h3></div></div></div><a class="indexterm" name="id4076"></a><a class="indexterm" name="id4078"></a><p>
4484 This property sets the current (default) database by executing a
4485 <code class="literal">USE</code> statement. The property can also be used
4486 to retrieve the current database name.
4487 </p><pre data-lang="python" class="programlisting">
4488 &gt;&gt;&gt; cnx.database = 'test'
4489 &gt;&gt;&gt; cnx.database = 'mysql'
4490 &gt;&gt;&gt; cnx.database
4491 u'mysql'
4492 </pre><p>
4493 Returns a string.
4494 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-get-warnings"></a>10.2.45 MySQLConnection.get_warnings Property</h3></div></div></div><a class="indexterm" name="id4086"></a><a class="indexterm" name="id4088"></a><p>
4495 This property can be assigned a value of <code class="literal">True</code>
4496 or <code class="literal">False</code> to enable or disable whether
4497 warnings should be fetched automatically. The default is
4498 <code class="literal">False</code> (default). The property can be invoked
4499 to retrieve the current warnings setting.
4500 </p><p>
4501 Fetching warnings automatically can be useful when debugging
4502 queries. Cursors make warnings available through the method
4503 <a class="link" href="#connector-python-api-mysqlcursor-fetchwarnings" title="10.5.14 MySQLCursor.fetchwarnings() Method">MySQLCursor.fetchwarnings()</a>.
4504 </p><pre data-lang="python" class="programlisting">
4505 &gt;&gt;&gt; cnx.get_warnings = True
4506 &gt;&gt;&gt; cursor.execute('SELECT "a"+1')
4507 &gt;&gt;&gt; cursor.fetchall()
4508 [(1.0,)]
4509 &gt;&gt;&gt; cursor.fetchwarnings()
4510 [(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]
4511 </pre><p>
4512 Returns <code class="literal">True</code> or <code class="literal">False</code>.
4513 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-in-transaction"></a>10.2.46 MySQLConnection.in_transaction Property</h3></div></div></div><a class="indexterm" name="id4102"></a><a class="indexterm" name="id4104"></a><p>
4514 This property returns <code class="literal">True</code> or
4515 <code class="literal">False</code> to indicate whether a transaction is
4516 active for the connection. The value is <code class="literal">True</code>
4517 regardless of whether you start a transaction using the
4518 <a class="link" href="#connector-python-api-mysqlconnection-start-transaction" title="10.2.34 MySQLConnection.start_transaction() Method"><code class="literal">start_transaction()</code></a>
4519 API call or by directly executing an SQL statement such as
4520 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/commit.html" target="_top"><code class="literal">START
4521 TRANSACTION</code></a> or
4522 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/commit.html" target="_top"><code class="literal">BEGIN</code></a>.
4523 </p><pre data-lang="python" class="programlisting">
4524 &gt;&gt;&gt; cnx.start_transaction()
4525 &gt;&gt;&gt; cnx.in_transaction
4526 True
4527 &gt;&gt;&gt; cnx.commit()
4528 &gt;&gt;&gt; cnx.in_transaction
4529 False
4530 </pre><p>
4531 <code class="literal">in_transaction</code> was added in MySQL Connector/Python 1.1.0.
4532 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-raise-on-warnings"></a>10.2.47 MySQLConnection.raise_on_warnings Property</h3></div></div></div><a class="indexterm" name="id4121"></a><a class="indexterm" name="id4123"></a><p>
4533 This property can be assigned a value of <code class="literal">True</code>
4534 or <code class="literal">False</code> to enable or disable whether
4535 warnings should raise exceptions. The default is
4536 <code class="literal">False</code> (default). The property can be invoked
4537 to retrieve the current exceptions setting.
4538 </p><p>
4539 Setting <code class="literal">raise_on_warnings</code> also sets
4540 <code class="literal">get_warnings</code> because warnings need to be
4541 fetched so they can be raised as exceptions.
4542 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
4543 You might always want to set the SQL mode if you would like to
4544 have the MySQL server directly report warnings as errors (see
4545 <a class="xref" href="#connector-python-api-mysqlconnection-sql-mode" title="10.2.52 MySQLConnection.sql_mode Property">Section 10.2.52, “MySQLConnection.sql_mode Property”</a>).
4546 It is also good to use transactional engines so transactions
4547 can be rolled back when catching the exception.
4548 </p></div><p>
4549 Result sets needs to be fetched completely before any exception
4550 can be raised. The following example shows the execution of a
4551 query that produces a warning:
4552 </p><pre data-lang="python" class="programlisting">
4553 &gt;&gt;&gt; cnx.raise_on_warnings = True
4554 &gt;&gt;&gt; cursor.execute('SELECT "a"+1')
4555 &gt;&gt;&gt; cursor.fetchall()
4556 ..
4557 mysql.connector.errors.DataError: 1292: Truncated incorrect DOUBLE value: 'a'
4558 </pre><p>
4559 Returns <code class="literal">True</code> or <code class="literal">False</code>.
4560 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-server-host"></a>10.2.48 MySQLConnection.server_host Property</h3></div></div></div><a class="indexterm" name="id4142"></a><a class="indexterm" name="id4144"></a><p>
4561 This read-only property returns the host name or IP address used
4562 for connecting to the MySQL server.
4563 </p><p>
4564 Returns a string.
4565 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-server-info"></a>10.2.49 MySQLConnection.server_info Property</h3></div></div></div><a class="indexterm" name="id4150"></a><a class="indexterm" name="id4152"></a><p>
4566 This read-only property returns the MySQL server information
4567 verbatim as a string: for example <code class="literal">8.4.0-log</code>,
4568 or <code class="literal">None</code> when not connected.
4569 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-server-port"></a>10.2.50 MySQLConnection.server_port Property</h3></div></div></div><a class="indexterm" name="id4159"></a><a class="indexterm" name="id4161"></a><p>
4570 This read-only property returns the TCP/IP port used for
4571 connecting to the MySQL server.
4572 </p><p>
4573 Returns an integer.
4574 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-server-version"></a>10.2.51 MySQLConnection.server_version Property</h3></div></div></div><a class="indexterm" name="id4167"></a><a class="indexterm" name="id4169"></a><p>
4575 This read-only property returns the MySQL server version as a
4576 tuple, or <code class="literal">None</code> when not connected.
4577 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-sql-mode"></a>10.2.52 MySQLConnection.sql_mode Property</h3></div></div></div><a class="indexterm" name="id4175"></a><a class="indexterm" name="id4177"></a><p>
4578 This property is used to retrieve and set the SQL Modes for the
4579 current connection. The value should be a list of different
4580 modes separated by comma (","), or a sequence of modes,
4581 preferably using the <code class="literal">constants.SQLMode</code> class.
4582 </p><p>
4583 To unset all modes, pass an empty string or an empty sequence.
4584 </p><pre data-lang="python" class="programlisting">
4585 &gt;&gt;&gt; cnx.sql_mode = 'TRADITIONAL,NO_ENGINE_SUBSTITUTION'
4586 &gt;&gt;&gt; cnx.sql_mode.split(',')
4587 [u'STRICT_TRANS_TABLES', u'STRICT_ALL_TABLES', u'NO_ZERO_IN_DATE',
4588 u'NO_ZERO_DATE', u'ERROR_FOR_DIVISION_BY_ZERO', u'TRADITIONAL',
4589 u'NO_AUTO_CREATE_USER', u'NO_ENGINE_SUBSTITUTION']
4590
4591 &gt;&gt;&gt; from mysql.connector.constants import SQLMode
4592 &gt;&gt;&gt; cnx.sql_mode = [ SQLMode.NO_ZERO_DATE, SQLMode.REAL_AS_FLOAT]
4593 &gt;&gt;&gt; cnx.sql_mode
4594 u'REAL_AS_FLOAT,NO_ZERO_DATE'
4595 </pre><p>
4596 Returns a string.
4597 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-time-zone"></a>10.2.53 MySQLConnection.time_zone Property</h3></div></div></div><a class="indexterm" name="id4186"></a><a class="indexterm" name="id4188"></a><p>
4598 This property is used to set or retrieve the time zone session
4599 variable for the current connection.
4600 </p><pre data-lang="python" class="programlisting">
4601 &gt;&gt;&gt; cnx.time_zone = '+00:00'
4602 &gt;&gt;&gt; cursor = cnx.cursor()
4603 &gt;&gt;&gt; cursor.execute('SELECT NOW()') ; cursor.fetchone()
4604 (datetime.datetime(2012, 6, 15, 11, 24, 36),)
4605 &gt;&gt;&gt; cnx.time_zone = '-09:00'
4606 &gt;&gt;&gt; cursor.execute('SELECT NOW()') ; cursor.fetchone()
4607 (datetime.datetime(2012, 6, 15, 2, 24, 44),)
4608 &gt;&gt;&gt; cnx.time_zone
4609 u'-09:00'
4610 </pre><p>
4611 Returns a string.
4612 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-use-unicode"></a>10.2.54 MySQLConnection.use_unicode Property</h3></div></div></div><a class="indexterm" name="id4195"></a><a class="indexterm" name="id4197"></a><p>
4613 This property sets and returns whether the connection uses
4614 Unicode with the value <code class="literal">True</code> or
4615 <code class="literal">False</code>.
4616
4617 </p><pre data-lang="python" class="programlisting"># gets whether the connector returns string fields as unicode or not
4618 print(cnx.use_unicode)
4619 &gt;&gt; True
4620
4621 # set or update use_unicode property
4622 cnx.use_unicode = False
4623 print(cnx.use_unicode)
4624 &gt;&gt; False</pre><p>
4625 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-unix-socket"></a>10.2.55 MySQLConnection.unix_socket Property</h3></div></div></div><a class="indexterm" name="id4205"></a><a class="indexterm" name="id4207"></a><p>
4626 This read-only property returns the Unix socket file for
4627 connecting to the MySQL server.
4628 </p><p>
4629 Returns a string.
4630 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-user"></a>10.2.56 MySQLConnection.user Property</h3></div></div></div><a class="indexterm" name="id4213"></a><a class="indexterm" name="id4215"></a><p>
4631 This read-only property returns the user name used for
4632 connecting to the MySQL server.
4633 </p><p>
4634 Returns a string.
4635 </p></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-mysqlconnectionpool"></a>10.3 pooling.MySQLConnectionPool Class</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-constructor">10.3.1 pooling.MySQLConnectionPool Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-add-connection">10.3.2 MySQLConnectionPool.add_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-get-connection">10.3.3 MySQLConnectionPool.get_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-set-config">10.3.4 MySQLConnectionPool.set_config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-pool-name">10.3.5 MySQLConnectionPool.pool_name Property</a></span></dt></dl></div><a class="indexterm" name="id4221"></a><a class="indexterm" name="id4223"></a><p>
4636 This class provides for the instantiation and management of
4637 connection pools.
4638 </p><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnectionpool-constructor"></a>10.3.1 pooling.MySQLConnectionPool Constructor</h3></div></div></div><a class="indexterm" name="id4228"></a><a class="indexterm" name="id4230"></a><p>
4639 Syntax:
4640 </p><pre data-lang="python" class="programlisting">MySQLConnectionPool(pool_name=None,
4641 pool_size=5,
4642 pool_reset_session=True,
4643 **kwargs)
4644 </pre><p>
4645 This constructor instantiates an object that manages a
4646 connection pool.
4647 </p><p>
4648 Arguments:
4649 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
4650 <code class="literal">pool_name</code>: The pool name. If this
4651 argument is not given, Connector/Python automatically generates the
4652 name, composed from whichever of the
4653 <code class="literal">host</code>, <code class="literal">port</code>,
4654 <code class="literal">user</code>, and <code class="literal">database</code>
4655 connection arguments are given in <code class="literal">kwargs</code>,
4656 in that order.
4657 </p><p>
4658 It is not an error for multiple pools to have the same name.
4659 An application that must distinguish pools by their
4660 <code class="literal">pool_name</code> property should create each
4661 pool with a distinct name.
4662 </p></li><li class="listitem"><p>
4663 <code class="literal">pool_size</code>: The pool size. If this
4664 argument is not given, the default is 5.
4665 </p></li><li class="listitem"><p>
4666 <code class="literal">pool_reset_session</code>: Whether to reset
4667 session variables when the connection is returned to the
4668 pool. This argument was added in Connector/Python 1.1.5. Before 1.1.5,
4669 session variables are not reset.
4670 </p></li><li class="listitem"><p>
4671 <code class="literal">kwargs</code>: Optional additional connection
4672 arguments, as described in
4673 <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
4674 </p></li></ul></div><p>
4675 Example:
4676 </p><pre data-lang="python" class="programlisting">dbconfig = {
4677 "database": "test",
4678 "user": "joe",
4679 }
4680
4681 cnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name = "mypool",
4682 pool_size = 3,
4683 **dbconfig)
4684 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnectionpool-add-connection"></a>10.3.2 MySQLConnectionPool.add_connection() Method</h3></div></div></div><a class="indexterm" name="id4261"></a><a class="indexterm" name="id4263"></a><p>
4685 Syntax:
4686 </p><pre data-lang="python" class="programlisting">cnxpool.add_connection(cnx = None)
4687 </pre><p>
4688 This method adds a new or existing
4689 <code class="literal">MySQLConnection</code> to the pool, or raises a
4690 <code class="literal">PoolError</code> if the pool is full.
4691 </p><p>
4692 Arguments:
4693 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
4694 <code class="literal">cnx</code>: The
4695 <code class="literal">MySQLConnection</code> object to be added to the
4696 pool. If this argument is missing, the pool creates a new
4697 connection and adds it.
4698 </p></li></ul></div><p>
4699 Example:
4700 </p><pre data-lang="python" class="programlisting">cnxpool.add_connection() # add new connection to pool
4701 cnxpool.add_connection(cnx) # add existing connection to pool
4702 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnectionpool-get-connection"></a>10.3.3 MySQLConnectionPool.get_connection() Method</h3></div></div></div><a class="indexterm" name="id4280"></a><a class="indexterm" name="id4282"></a><p>
4703 Syntax:
4704 </p><pre data-lang="python" class="programlisting">cnxpool.get_connection()
4705 </pre><p>
4706 This method returns a connection from the pool, or raises a
4707 <code class="literal">PoolError</code> if no connections are available.
4708 </p><p>
4709 Example:
4710 </p><pre data-lang="python" class="programlisting">cnx = cnxpool.get_connection()
4711 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnectionpool-set-config"></a>10.3.4 MySQLConnectionPool.set_config() Method</h3></div></div></div><a class="indexterm" name="id4292"></a><a class="indexterm" name="id4294"></a><p>
4712 Syntax:
4713 </p><pre data-lang="python" class="programlisting">cnxpool.set_config(**kwargs)
4714 </pre><p>
4715 This method sets the configuration parameters for connections in
4716 the pool. Connections requested from the pool after the
4717 configuration change use the new parameters. Connections
4718 obtained before the change remain unaffected, but when they are
4719 closed (returned to the pool) are reopened with the new
4720 parameters before being returned by the pool for subsequent
4721 connection requests.
4722 </p><p>
4723 Arguments:
4724 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
4725 <code class="literal">kwargs</code>: Connection arguments.
4726 </p></li></ul></div><p>
4727 Example:
4728 </p><pre data-lang="python" class="programlisting">dbconfig = {
4729 "database": "performance_schema",
4730 "user": "admin",
4731 "password": "<em class="replaceable"><code>password</code></em>",
4732 }
4733
4734 cnxpool.set_config(**dbconfig)
4735 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnectionpool-pool-name"></a>10.3.5 MySQLConnectionPool.pool_name Property</h3></div></div></div><a class="indexterm" name="id4309"></a><a class="indexterm" name="id4311"></a><p>
4736 Syntax:
4737 </p><pre data-lang="python" class="programlisting">cnxpool.pool_name
4738 </pre><p>
4739 This property returns the connection pool name.
4740 </p><p>
4741 Example:
4742 </p><pre data-lang="python" class="programlisting">name = cnxpool.pool_name
4743 </pre></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-pooledmysqlconnection"></a>10.4 pooling.PooledMySQLConnection Class</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-constructor">10.4.1 pooling.PooledMySQLConnection Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-close">10.4.2 PooledMySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-config">10.4.3 PooledMySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-pool-name">10.4.4 PooledMySQLConnection.pool_name Property</a></span></dt></dl></div><a class="indexterm" name="id4320"></a><a class="indexterm" name="id4322"></a><p>
4744 This class is used by <code class="literal">MySQLConnectionPool</code> to
4745 return a pooled connection instance. It is also the class used for
4746 connections obtained with calls to the
4747 <code class="literal">connect()</code> method that name a connection pool
4748 (see <a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>).
4749 </p><p>
4750 <code class="literal">PooledMySQLConnection</code> pooled connection objects
4751 are similar to <code class="literal">MySQLConnection</code> unpooled
4752 connection objects, with these differences:
4753 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
4754 To release a pooled connection obtained from a connection
4755 pool, invoke its <code class="literal">close()</code> method, just as
4756 for any unpooled connection. However, for a pooled connection,
4757 <code class="literal">close()</code> does not actually close the
4758 connection but returns it to the pool and makes it available
4759 for subsequent connection requests.
4760 </p></li><li class="listitem"><p>
4761 A pooled connection cannot be reconfigured using its
4762 <code class="literal">config()</code> method. Connection changes must be
4763 done through the pool object itself, as described by
4764 <a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>.
4765 </p></li><li class="listitem"><p>
4766 A pooled connection has a <code class="literal">pool_name</code>
4767 property that returns the pool name.
4768 </p></li></ul></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-pooledmysqlconnection-constructor"></a>10.4.1 pooling.PooledMySQLConnection Constructor</h3></div></div></div><a class="indexterm" name="id4345"></a><a class="indexterm" name="id4347"></a><p>
4769 Syntax:
4770 </p><pre data-lang="python" class="programlisting">PooledMySQLConnection(cnxpool, cnx)
4771 </pre><p>
4772 This constructor takes connection pool and connection arguments
4773 and returns a pooled connection. It is used by the
4774 <code class="literal">MySQLConnectionPool</code> class.
4775 </p><p>
4776 Arguments:
4777 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
4778 <code class="literal">cnxpool</code>: A
4779 <code class="literal">MySQLConnectionPool</code> instance.
4780 </p></li><li class="listitem"><p>
4781 <code class="literal">cnx</code>: A <code class="literal">MySQLConnection</code>
4782 instance.
4783 </p></li></ul></div><p>
4784 Example:
4785 </p><pre data-lang="python" class="programlisting">pcnx = mysql.connector.pooling.PooledMySQLConnection(cnxpool, cnx)
4786 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-pooledmysqlconnection-close"></a>10.4.2 PooledMySQLConnection.close() Method</h3></div></div></div><a class="indexterm" name="id4367"></a><a class="indexterm" name="id4369"></a><p>
4787 Syntax:
4788 </p><pre data-lang="python" class="programlisting">cnx.close()
4789 </pre><p>
4790 Returns a pooled connection to its connection pool.
4791 </p><p>
4792 For a pooled connection, <code class="literal">close()</code> does not
4793 actually close it but returns it to the pool and makes it
4794 available for subsequent connection requests.
4795 </p><p>
4796 If the pool configuration parameters are changed, a returned
4797 connection is closed and reopened with the new configuration
4798 before being returned from the pool again in response to a
4799 connection request.
4800 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-pooledmysqlconnection-config"></a>10.4.3 PooledMySQLConnection.config() Method</h3></div></div></div><a class="indexterm" name="id4379"></a><a class="indexterm" name="id4381"></a><p>
4801 For pooled connections, the <code class="literal">config()</code> method
4802 raises a <code class="literal">PoolError</code> exception. Configuration
4803 for pooled connections should be done using the pool object.
4804 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-pooledmysqlconnection-pool-name"></a>10.4.4 PooledMySQLConnection.pool_name Property</h3></div></div></div><a class="indexterm" name="id4388"></a><a class="indexterm" name="id4390"></a><p>
4805 Syntax:
4806 </p><pre data-lang="python" class="programlisting">cnx.pool_name
4807 </pre><p>
4808 This property returns the name of the connection pool to which
4809 the connection belongs.
4810 </p><p>
4811 Example:
4812 </p><pre data-lang="python" class="programlisting">cnx = cnxpool.get_connection()
4813 name = cnx.pool_name
4814 </pre></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-mysqlcursor"></a>10.5 cursor.MySQLCursor Class</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysqlcursor-constructor">10.5.1 cursor.MySQLCursor Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-add-attribute">10.5.2 MySQLCursor.add_attribute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-clear-attributes">10.5.3 MySQLCursor.clear_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-get-attributes">10.5.4 MySQLCursor.get_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-callproc">10.5.5 MySQLCursor.callproc() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-close">10.5.6 MySQLCursor.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-execute">10.5.7 MySQLCursor.execute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-executemany">10.5.8 MySQLCursor.executemany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchall">10.5.9 MySQLCursor.fetchall() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchmany">10.5.10 MySQLCursor.fetchmany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchone">10.5.11 MySQLCursor.fetchone() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-nextset">10.5.12 MySQLCursor.nextset() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchsets">10.5.13 MySQLCursor.fetchsets() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchwarnings">10.5.14 MySQLCursor.fetchwarnings() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-stored-results">10.5.15 MySQLCursor.stored_results() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-column-names">10.5.16 MySQLCursor.column_names Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-description">10.5.17 MySQLCursor.description Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-warnings">10.5.18 MySQLCursor.warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-lastrowid">10.5.19 MySQLCursor.lastrowid Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-rowcount">10.5.20 MySQLCursor.rowcount Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-statement">10.5.21 MySQLCursor.statement Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-with-rows">10.5.22 MySQLCursor.with_rows Property</a></span></dt></dl></div><a class="indexterm" name="id4399"></a><a class="indexterm" name="id4401"></a><p>
4815 The <code class="literal">MySQLCursor</code> class instantiates objects that
4816 can execute operations such as SQL statements. Cursor objects
4817 interact with the MySQL server using a
4818 <code class="literal">MySQLConnection</code> object.
4819 </p><p>
4820 To create a cursor, use the
4821 <a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
4822 method of a connection object:
4823 </p><pre data-lang="python" class="programlisting">import mysql.connector
4824
4825 cnx = mysql.connector.connect(database='world')
4826 cursor = cnx.cursor()
4827 </pre><p>
4828 Several related classes inherit from
4829 <code class="literal">MySQLCursor</code>. To create a cursor of one of these
4830 types, pass the appropriate arguments to
4831 <code class="literal">cursor()</code>:
4832 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
4833 <code class="literal">MySQLCursorBuffered</code> creates a buffered
4834 cursor. See
4835 <a class="xref" href="#connector-python-api-mysqlcursorbuffered" title="10.6.1 cursor.MySQLCursorBuffered Class">Section 10.6.1, “cursor.MySQLCursorBuffered Class”</a>.
4836 </p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(buffered=True)
4837 </pre></li><li class="listitem"><p>
4838 <code class="literal">MySQLCursorRaw</code> creates a raw cursor. See
4839 <a class="xref" href="#connector-python-api-mysqlcursorraw" title="10.6.2 cursor.MySQLCursorRaw Class">Section 10.6.2, “cursor.MySQLCursorRaw Class”</a>.
4840 </p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(raw=True)
4841 </pre></li><li class="listitem"><p>
4842 <code class="literal">MySQLCursorDict</code> creates a cursor that
4843 returns rows as dictionaries. See
4844 <a class="xref" href="#connector-python-api-mysqlcursordict" title="10.6.3 cursor.MySQLCursorDict Class">Section 10.6.3, “cursor.MySQLCursorDict Class”</a>.
4845 </p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(dictionary=True)
4846 </pre></li><li class="listitem"><p>
4847 <code class="literal">MySQLCursorBufferedDict</code> creates a buffered
4848 cursor that returns rows as dictionaries. See
4849 <a class="xref" href="#connector-python-api-mysqlcursorbuffereddict" title="10.6.4 cursor.MySQLCursorBufferedDict Class">Section 10.6.4, “cursor.MySQLCursorBufferedDict Class”</a>.
4850 </p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(dictionary=True, buffered=True)
4851 </pre></li><li class="listitem"><p>
4852 <code class="literal">MySQLCursorPrepared</code> creates a cursor for
4853 executing prepared statements. See
4854 <a class="xref" href="#connector-python-api-mysqlcursorprepared" title="10.6.5 cursor.MySQLCursorPrepared Class">Section 10.6.5, “cursor.MySQLCursorPrepared Class”</a>.
4855 </p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(prepared=True)
4856 </pre></li></ul></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-constructor"></a>10.5.1 cursor.MySQLCursor Constructor</h3></div></div></div><a class="indexterm" name="id4441"></a><a class="indexterm" name="id4443"></a><p>
4857 In most cases, the <code class="literal">MySQLConnection</code>
4858 <a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
4859 method is used to instantiate a <code class="literal">MySQLCursor</code>
4860 object:
4861 </p><pre data-lang="python" class="programlisting">import mysql.connector
4862
4863 cnx = mysql.connector.connect(database='world')
4864 cursor = cnx.cursor()
4865 </pre><p>
4866 It is also possible to instantiate a cursor by passing a
4867 <a class="link" href="#connector-python-api-mysqlconnection" title="10.2 connection.MySQLConnection Class"><code class="literal">MySQLConnection</code></a>
4868 object to <code class="literal">MySQLCursor</code>:
4869 </p><pre data-lang="python" class="programlisting">import mysql.connector
4870 from mysql.connector.cursor import MySQLCursor
4871
4872 cnx = mysql.connector.connect(database='world')
4873 cursor = MySQLCursor(cnx)
4874 </pre><p>
4875 The connection argument is optional. If omitted, the cursor is
4876 created but its
4877 <a class="link" href="#connector-python-api-mysqlcursor-execute" title="10.5.7 MySQLCursor.execute() Method"><code class="literal">execute()</code></a>
4878 method raises an exception.
4879 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-add-attribute"></a>10.5.2 MySQLCursor.add_attribute() Method</h3></div></div></div><a class="indexterm" name="id4461"></a><a class="indexterm" name="id4463"></a><p>
4880 Syntax:
4881 </p><pre data-lang="python" class="programlisting">cursor.add_attribute(name, value)
4882 </pre><p>
4883 Adds a new named query attribute to the list, as part of MySQL
4884 server's <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/query-attributes.html" target="_top">Query Attributes</a> functionality.
4885 </p><p>
4886 <code class="literal">name</code>: The name must be a string, but no other
4887 validation checks are made; attributes are sent as is to the
4888 server and errors, if any, will be detected and reported by the
4889 server.
4890 </p><p>
4891 <code class="literal">value</code>: a value converted to the MySQL Binary
4892 Protocol, similar to how prepared statement parameters are
4893 converted. An error is reported if the conversion fails.
4894 </p><p>
4895 Query attributes must be enabled on the server, and are disabled
4896 by default. A warning is logged when setting query attributes
4897 server connection that does not support them. See also
4898 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/query-attributes.html#query-attributes-prerequisites" target="_top">Prerequisites for Using Query Attributes</a> for enabling
4899 the query_attributes MySQL server component.
4900 </p><p>
4901 Example query attribute usage:
4902 </p><pre data-lang="python" class="programlisting"># Each invocation of `add_attribute` method will add a new query attribute:
4903 cur.add_attribute("foo", 2)
4904 cur.execute("SELECT first_name, last_name FROM clients")
4905 # The query above sent attibute "foo" with value 2.
4906
4907 cur.add_attribute(*("bar", "3"))
4908 cur.execute("SELECT * FROM products WHERE price &lt; ?", 10)
4909 # The query above sent attributes ("foo", 2) and ("bar", "3").
4910
4911 my_attributes = [("page_name", "root"), ("previous_page", "login")]
4912 for attribute_tuple in my_attributes:
4913 cur.add_attribute(*attribute_tuple)
4914 cur.execute("SELECT * FROM offers WHERE publish = ?", 0)
4915 # The query above sent 4 attributes.
4916
4917 # To check the current query attributes:
4918
4919 print(cur.get_attributes())
4920 # prints:
4921 [("foo", 2), ("bar", "3"), ("page_name", "root"), ("previous_page", "login")]
4922
4923 # Query attributes are not cleared until the cursor is closed or
4924 # of the clear_attributes() method is invoked:
4925
4926 cur.clear_attributes()
4927 print(cur.get_attributes())
4928 # prints:
4929 []
4930 cur.execute("SELECT first_name, last_name FROM clients")
4931 # The query above did not send any attibute.
4932 </pre><p>
4933 This method was added in Connector/Python 8.0.26.
4934 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-clear-attributes"></a>10.5.3 MySQLCursor.clear_attributes() Method</h3></div></div></div><a class="indexterm" name="id4480"></a><a class="indexterm" name="id4482"></a><p>
4935 Syntax:
4936 </p><pre data-lang="python" class="programlisting">cursor.clear_attributes()
4937 </pre><p>
4938 Clear the list of query attributes on the connector's side, as
4939 set by
4940 <a class="xref" href="#connector-python-api-mysqlcursor-add-attribute" title="10.5.2 MySQLCursor.add_attribute() Method">Section 10.5.2, “MySQLCursor.add_attribute() Method”</a>.
4941 </p><p>
4942 This method was added in Connector/Python 8.0.26.
4943 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-get-attributes"></a>10.5.4 MySQLCursor.get_attributes() Method</h3></div></div></div><a class="indexterm" name="id4491"></a><a class="indexterm" name="id4493"></a><p>
4944 Syntax:
4945 </p><pre data-lang="python" class="programlisting">cursor.get_attributes()
4946 </pre><p>
4947 Return a list of existing query attributes, as set by
4948 <a class="xref" href="#connector-python-api-mysqlcursor-add-attribute" title="10.5.2 MySQLCursor.add_attribute() Method">Section 10.5.2, “MySQLCursor.add_attribute() Method”</a>.
4949 </p><p>
4950 This method was added in Connector/Python 8.0.26.
4951 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-callproc"></a>10.5.5 MySQLCursor.callproc() Method</h3></div></div></div><a class="indexterm" name="id4502"></a><a class="indexterm" name="id4504"></a><p>
4952 Syntax:
4953 </p><pre data-lang="python" class="programlisting">result_args = cursor.callproc(proc_name, args=())
4954 </pre><p>
4955 This method calls the stored procedure named by the
4956 <code class="literal">proc_name</code> argument. The
4957 <code class="literal">args</code> sequence of parameters must contain one
4958 entry for each argument that the procedure expects.
4959 <code class="literal">callproc()</code> returns a modified copy of the
4960 input sequence. Input parameters are left untouched. Output and
4961 input/output parameters may be replaced with new values.
4962 </p><p>
4963 Result sets produced by the stored procedure are automatically
4964 fetched and stored as
4965 <a class="link" href="#connector-python-api-mysqlcursorbuffered" title="10.6.1 cursor.MySQLCursorBuffered Class">MySQLCursorBuffered</a>
4966 instances. For more information about using these result sets,
4967 see
4968 <a class="link" href="#connector-python-api-mysqlcursor-stored-results" title="10.5.15 MySQLCursor.stored_results() Method"><code class="literal">stored_results()</code></a>.
4969 </p><p>
4970 Suppose that a stored procedure takes two parameters, multiplies
4971 the values, and returns the product:
4972 </p><pre data-lang="sql" class="programlisting">CREATE PROCEDURE multiply(IN pFac1 INT, IN pFac2 INT, OUT pProd INT)
4973 BEGIN
4974 SET pProd := pFac1 * pFac2;
4975 END;
4976 </pre><p>
4977 The following example shows how to execute the
4978 <code class="literal">multiply()</code> procedure:
4979 </p><pre data-lang="python" class="programlisting">&gt;&gt;&gt; args = (5, 6, 0) # 0 is to hold value of the OUT parameter pProd
4980 &gt;&gt;&gt; cursor.callproc('multiply', args)
4981 ('5', '6', 30L)
4982 </pre><p>
4983 Connector/Python 1.2.1 and up permits parameter types to be specified. To
4984 do this, specify a parameter as a two-item tuple consisting of
4985 the parameter value and type. Suppose that a procedure
4986 <code class="literal">sp1()</code> has this definition:
4987 </p><pre data-lang="sql" class="programlisting">CREATE PROCEDURE sp1(IN pStr1 VARCHAR(20), IN pStr2 VARCHAR(20),
4988 OUT pConCat VARCHAR(100))
4989 BEGIN
4990 SET pConCat := CONCAT(pStr1, pStr2);
4991 END;
4992 </pre><p>
4993 To execute this procedure from Connector/Python, specifying a type for the
4994 <code class="literal">OUT</code> parameter, do this:
4995 </p><pre data-lang="python" class="programlisting">args = ('ham', 'eggs', (0, 'CHAR'))
4996 result_args = cursor.callproc('sp1', args)
4997 print(result_args[2])
4998 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-close"></a>10.5.6 MySQLCursor.close() Method</h3></div></div></div><a class="indexterm" name="id4529"></a><a class="indexterm" name="id4531"></a><p>
4999 Syntax:
5000 </p><pre data-lang="python" class="programlisting">cursor.close()
5001 </pre><p>
5002 Use <code class="literal">close()</code> when you are done using a cursor.
5003 This method closes the cursor, resets all results, and ensures
5004 that the cursor object has no reference to its original
5005 connection object.
5006 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-execute"></a>10.5.7 MySQLCursor.execute() Method</h3></div></div></div><a class="indexterm" name="id4539"></a><a class="indexterm" name="id4541"></a><p>
5007 Syntax:
5008 </p><pre data-lang="python" class="programlisting">cursor.execute(operation, params=None)
5009 iterator = cursor.execute(operation, params=None)
5010
5011 # Allowed before 9.2.0
5012 iterator = cursor.execute(operation, params=None, multi=True)
5013 </pre><p>
5014 This method executes the given database
5015 <code class="literal">operation</code> (query or command). The parameters
5016 found in the tuple or dictionary <code class="literal">params</code> are
5017 bound to the variables in the operation. Specify variables using
5018 <code class="literal">%s</code> or
5019 <code class="literal">%(<em class="replaceable"><code>name</code></em>)s</code> parameter
5020 style (that is, using <code class="literal">format</code> or
5021 <code class="literal">pyformat</code> style).
5022 </p><p>
5023 Before Connector/Python 9.2.0, <code class="literal">execute()</code> accepted a
5024 <code class="literal">multi</code> option and returned an iterator if set
5025 to <code class="literal">True</code>. That option was removed in 9.2.0,
5026 and <a class="xref" href="#connector-python-multi" title="9.3 Executing Multiple Statements">Section 9.3, “Executing Multiple Statements”</a> was added.
5027 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
5028 In Python, a tuple containing a single value must include a
5029 comma. For example, <span class="emphasis"><em>('abc')</em></span> is evaluated
5030 as a scalar while <span class="emphasis"><em>('abc',)</em></span> is evaluated
5031 as a tuple.
5032 </p></div><p>
5033 This example inserts information about a new employee, then
5034 selects the data for that person. The statements are executed as
5035 separate <code class="literal">execute()</code> operations:
5036 </p><pre data-lang="python" class="programlisting">insert_stmt = (
5037 "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
5038 "VALUES (%s, %s, %s, %s)"
5039 )
5040 data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
5041 cursor.execute(insert_stmt, data)
5042
5043 select_stmt = "SELECT * FROM employees WHERE emp_no = %(emp_no)s"
5044 cursor.execute(select_stmt, { 'emp_no': 2 })
5045 </pre><p>
5046 The data values are converted as necessary from Python objects
5047 to something MySQL understands. In the preceding example, the
5048 <code class="literal">datetime.date()</code> instance is converted to
5049 <code class="literal">'2012-03-23'</code>.
5050 </p><p>
5051 If the connection is configured to fetch warnings, warnings
5052 generated by the operation are available through the
5053 <a class="link" href="#connector-python-api-mysqlcursor-fetchwarnings" title="10.5.14 MySQLCursor.fetchwarnings() Method">MySQLCursor.fetchwarnings()</a>
5054 method.
5055 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-executemany"></a>10.5.8 MySQLCursor.executemany() Method</h3></div></div></div><a class="indexterm" name="id4572"></a><a class="indexterm" name="id4574"></a><p>
5056 Syntax:
5057 </p><pre data-lang="python" class="programlisting">cursor.executemany(operation, seq_of_params)
5058 </pre><p>
5059 This method prepares a database <code class="literal">operation</code>
5060 (query or command) and executes it against all parameter
5061 sequences or mappings found in the sequence
5062 <code class="literal">seq_of_params</code>.
5063 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
5064 In Python, a tuple containing a single value must include a
5065 comma. For example, <span class="emphasis"><em>('abc')</em></span> is evaluated
5066 as a scalar while <span class="emphasis"><em>('abc',)</em></span> is evaluated
5067 as a tuple.
5068 </p></div><p>
5069 In most cases, the <code class="literal">executemany()</code> method
5070 iterates through the sequence of parameters, each time passing
5071 the current parameters to the <code class="literal">execute()</code>
5072 method.
5073 </p><p>
5074 An optimization is applied for inserts: The data values given by
5075 the parameter sequences are batched using multiple-row syntax.
5076 The following example inserts three records:
5077 </p><pre data-lang="python" class="programlisting">data = [
5078 ('Jane', date(2005, 2, 12)),
5079 ('Joe', date(2006, 5, 23)),
5080 ('John', date(2010, 10, 3)),
5081 ]
5082 stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
5083 cursor.executemany(stmt, data)
5084 </pre><p>
5085 For the preceding example, the
5086 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a> statement sent to MySQL
5087 is:
5088 </p><pre data-lang="sql" class="programlisting">INSERT INTO employees (first_name, hire_date)
5089 VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')
5090 </pre><p>
5091 With the <code class="literal">executemany()</code> method, it is not
5092 possible to specify multiple statements to execute in the
5093 <code class="literal">operation</code> argument. Doing so raises an
5094 <code class="literal">InternalError</code> exception. Consider using
5095 <a class="xref" href="#connector-python-multi" title="9.3 Executing Multiple Statements">Section 9.3, “Executing Multiple Statements”</a> instead.
5096 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-fetchall"></a>10.5.9 MySQLCursor.fetchall() Method</h3></div></div></div><a class="indexterm" name="id4601"></a><a class="indexterm" name="id4603"></a><p>
5097 Syntax:
5098 </p><pre data-lang="python" class="programlisting">rows = cursor.fetchall()
5099 </pre><p>
5100 The method fetches all (or all remaining) rows of a query result
5101 set and returns a list of tuples. If no more rows are available,
5102 it returns an empty list.
5103 </p><p>
5104 The following example shows how to retrieve the first two rows
5105 of a result set, and then retrieve any remaining rows:
5106 </p><pre data-lang="python" class="programlisting">&gt;&gt;&gt; cursor.execute("SELECT * FROM employees ORDER BY emp_no")
5107 &gt;&gt;&gt; head_rows = cursor.fetchmany(size=2)
5108 &gt;&gt;&gt; remaining_rows = cursor.fetchall()
5109 </pre><p>
5110 You must fetch all rows for the current query before executing
5111 new statements using the same connection.
5112 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-fetchmany"></a>10.5.10 MySQLCursor.fetchmany() Method</h3></div></div></div><a class="indexterm" name="id4613"></a><a class="indexterm" name="id4615"></a><p>
5113 Syntax:
5114 </p><pre data-lang="python" class="programlisting">rows = cursor.fetchmany(size=1)
5115 </pre><p>
5116 This method fetches the next set of rows of a query result and
5117 returns a list of tuples. If no more rows are available, it
5118 returns an empty list.
5119 </p><p>
5120 The number of rows returned can be specified using the
5121 <code class="literal">size</code> argument, which defaults to one. Fewer
5122 rows are returned if fewer rows are available than specified.
5123 </p><p>
5124 You must fetch all rows for the current query before executing
5125 new statements using the same connection.
5126 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-fetchone"></a>10.5.11 MySQLCursor.fetchone() Method</h3></div></div></div><a class="indexterm" name="id4625"></a><a class="indexterm" name="id4627"></a><p>
5127 Syntax:
5128 </p><pre data-lang="python" class="programlisting">row = cursor.fetchone()
5129 </pre><p>
5130 This method retrieves the next row of a query result set and
5131 returns a single sequence, or <code class="literal">None</code> if no more
5132 rows are available. By default, the returned tuple consists of
5133 data returned by the MySQL server, converted to Python objects.
5134 If the cursor is a raw cursor, no such conversion occurs; see
5135 <a class="xref" href="#connector-python-api-mysqlcursorraw" title="10.6.2 cursor.MySQLCursorRaw Class">Section 10.6.2, “cursor.MySQLCursorRaw Class”</a>.
5136 </p><p>
5137 The <code class="literal">fetchone()</code> method is used by
5138 <a class="link" href="#connector-python-api-mysqlcursor-fetchall" title="10.5.9 MySQLCursor.fetchall() Method">fetchall()</a>
5139 and
5140 <a class="link" href="#connector-python-api-mysqlcursor-fetchmany" title="10.5.10 MySQLCursor.fetchmany() Method">fetchmany()</a>.
5141 It is also used when a cursor is used as an iterator.
5142 </p><p>
5143 The following example shows two equivalent ways to process a
5144 query result. The first uses <code class="literal">fetchone()</code> in a
5145 <code class="literal">while</code> loop, the second uses the cursor as an
5146 iterator:
5147 </p><pre data-lang="python" class="programlisting"># Using a while loop
5148 cursor.execute("SELECT * FROM employees")
5149 row = cursor.fetchone()
5150 while row is not None:
5151 print(row)
5152 row = cursor.fetchone()
5153
5154 # Using the cursor as iterator
5155 cursor.execute("SELECT * FROM employees")
5156 for row in cursor:
5157 print(row)
5158 </pre><p>
5159 You must fetch all rows for the current query before executing
5160 new statements using the same connection.
5161 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-nextset"></a>10.5.12 MySQLCursor.nextset() Method</h3></div></div></div><a class="indexterm" name="id4645"></a><a class="indexterm" name="id4647"></a><p>
5162 Syntax:
5163 </p><pre data-lang="python" class="programlisting">row = cursor.nextset()
5164 </pre><p>
5165 This method makes the cursor skip to the next available set,
5166 discarding any remaining rows from the current set. It returns
5167 <code class="literal">None</code> if there are no more sets or returns
5168 <code class="literal">True</code> and subsequent calls to the
5169 cursor.fetch*() methods returns rows from the next result set.
5170 </p><p>
5171 This method can be used as part of the multi statement execution
5172 workflow.
5173 </p><pre data-lang="python" class="programlisting">sql_operation = '''
5174 SET @a=1, @b='2025-01-01';
5175 SELECT @a, LENGTH('hello'), @b;
5176 SELECT @@version;
5177 '''
5178 with cnx.cursor() as cur:
5179 cur.execute(sql_operation)
5180
5181 result_set = cur.fetchall()
5182 # do something with result set
5183 ...
5184
5185 while cur.nextset():
5186 result_set = cur.fetchall()
5187 # do something with result set
5188 </pre><p>
5189 This method was added in Connector/Python 9.2.0.
5190 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-fetchsets"></a>10.5.13 MySQLCursor.fetchsets() Method</h3></div></div></div><a class="indexterm" name="id4659"></a><a class="indexterm" name="id4661"></a><p>
5191 Syntax:
5192 </p><pre data-lang="python" class="programlisting">for statement, result_set in cursor.fetchsets():
5193 # do something with statement and/or result set
5194 </pre><p>
5195 This method generates a set of result sets caused by the last
5196 cursor.execute*(). It returns a generator where each item is a
5197 2-tuple; the first element is the statement that caused the
5198 result set, and the second is the result set itself.
5199 </p><p>
5200 This method can be used as part of the multi statement execution
5201 workflow.
5202 </p><pre data-lang="python" class="programlisting"> sql_operation = '''
5203 SET @a=1, @b='2025-01-01';
5204 SELECT @a, LENGTH('hello'), @b;
5205 SELECT @@version;
5206 '''
5207 with cnx.cursor() as cur:
5208 cur.execute(sql_operation)
5209 for statement, result_set in cur.fetchsets():
5210 # do something with statement and/or result set
5211 </pre><p>
5212 This method was added in Connector/Python 9.2.0.
5213 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-fetchwarnings"></a>10.5.14 MySQLCursor.fetchwarnings() Method</h3></div></div></div><a class="indexterm" name="id4671"></a><a class="indexterm" name="id4673"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
5214 This method has been deprecated as of 9.3.0. Use the property
5215 method
5216 <a class="xref" href="#connector-python-api-mysqlcursor-warnings" title="10.5.18 MySQLCursor.warnings Property">Section 10.5.18, “MySQLCursor.warnings Property”</a>
5217 instead.
5218 </p></div><p>
5219 Syntax:
5220 </p><pre data-lang="python" class="programlisting">tuples = cursor.fetchwarnings()
5221 </pre><p>
5222 This method returns a list of tuples containing warnings
5223 generated by the previously executed operation. To set whether
5224 to fetch warnings, use the connection's
5225 <a class="link" href="#connector-python-api-mysqlconnection-get-warnings" title="10.2.45 MySQLConnection.get_warnings Property"><code class="literal">get_warnings</code></a>
5226 property.
5227 </p><p>
5228 The following example shows a
5229 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a> statement that generates a
5230 warning:
5231 </p><pre data-lang="python" class="programlisting">&gt;&gt;&gt; cnx.get_warnings = True
5232 &gt;&gt;&gt; cursor.execute("SELECT 'a'+1")
5233 &gt;&gt;&gt; cursor.fetchall()
5234 [(1.0,)]
5235 &gt;&gt;&gt; cursor.fetchwarnings()
5236 [(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]
5237 </pre><p>
5238 When warnings are generated, it is possible to raise errors
5239 instead, using the connection's
5240 <a class="link" href="#connector-python-api-mysqlconnection-raise-on-warnings" title="10.2.47 MySQLConnection.raise_on_warnings Property"><code class="literal">raise_on_warnings</code></a>
5241 property.
5242 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-stored-results"></a>10.5.15 MySQLCursor.stored_results() Method</h3></div></div></div><a class="indexterm" name="id4693"></a><a class="indexterm" name="id4695"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
5243 This method has been deprecated as of 9.3.0.
5244 </p></div><p>
5245 Syntax:
5246 </p><pre data-lang="python" class="programlisting">iterator = cursor.stored_results()
5247 </pre><p>
5248 This method returns a list iterator object that can be used to
5249 process result sets produced by a stored procedure executed
5250 using the
5251 <a class="link" href="#connector-python-api-mysqlcursor-callproc" title="10.5.5 MySQLCursor.callproc() Method">callproc()</a>
5252 method. The result sets remain available until you use the
5253 cursor to execute another operation or call another stored
5254 procedure.
5255 </p><p>
5256 The following example executes a stored procedure that produces
5257 two result sets, then uses <code class="literal">stored_results()</code>
5258 to retrieve them:
5259 </p><pre data-lang="python" class="programlisting">&gt;&gt;&gt; cursor.callproc('myproc')
5260 ()
5261 &gt;&gt;&gt; for result in cursor.stored_results():
5262 ... print result.fetchall()
5263 ...
5264 [(1,)]
5265 [(2,)]
5266 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-column-names"></a>10.5.16 MySQLCursor.column_names Property</h3></div></div></div><a class="indexterm" name="id4709"></a><a class="indexterm" name="id4711"></a><p>
5267 Syntax:
5268 </p><pre data-lang="python" class="programlisting">sequence = cursor.column_names
5269 </pre><p>
5270 This read-only property returns the column names of a result set
5271 as sequence of Unicode strings.
5272 </p><p>
5273 The following example shows how to create a dictionary from a
5274 tuple containing data with keys using
5275 <code class="literal">column_names</code>:
5276 </p><pre data-lang="python" class="programlisting">cursor.execute("SELECT last_name, first_name, hire_date "
5277 "FROM employees WHERE emp_no = %s", (123,))
5278 row = dict(zip(cursor.column_names, cursor.fetchone()))
5279 print("{last_name}, {first_name}: {hire_date}".format(row))
5280 </pre><p>
5281 Alternatively, as of Connector/Python 2.0.0, you can fetch rows as
5282 dictionaries directly; see
5283 <a class="xref" href="#connector-python-api-mysqlcursordict" title="10.6.3 cursor.MySQLCursorDict Class">Section 10.6.3, “cursor.MySQLCursorDict Class”</a>.
5284 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-description"></a>10.5.17 MySQLCursor.description Property</h3></div></div></div><a class="indexterm" name="id4723"></a><a class="indexterm" name="id4725"></a><p>
5285 Syntax:
5286 </p><pre data-lang="python" class="programlisting">tuples = cursor.description
5287 </pre><p>
5288 This read-only property returns a list of tuples describing the
5289 columns in a result set. Each tuple in the list contains values
5290 as follows:
5291 </p><pre data-lang="python" class="programlisting">(column_name,
5292 type,
5293 None,
5294 None,
5295 None,
5296 None,
5297 null_ok,
5298 column_flags)
5299 </pre><p>
5300 The following example shows how to interpret
5301 <code class="literal">description</code> tuples:
5302 </p><pre data-lang="python" class="programlisting">import mysql.connector
5303 from mysql.connector import FieldType
5304
5305 ...
5306
5307 cursor.execute("SELECT emp_no, last_name, hire_date "
5308 "FROM employees WHERE emp_no = %s", (123,))
5309 for i in range(len(cursor.description)):
5310 print("Column {}:".format(i+1))
5311 desc = cursor.description[i]
5312 print(" column_name = {}".format(desc[0]))
5313 print(" type = {} ({})".format(desc[1], FieldType.get_info(desc[1])))
5314 print(" null_ok = {}".format(desc[6]))
5315 print(" column_flags = {}".format(desc[7]))
5316 </pre><p>
5317 The output looks like this:
5318 </p><pre data-lang="python" class="programlisting">Column 1:
5319 column_name = emp_no
5320 type = 3 (LONG)
5321 null_ok = 0
5322 column_flags = 20483
5323 Column 2:
5324 column_name = last_name
5325 type = 253 (VAR_STRING)
5326 null_ok = 0
5327 column_flags = 4097
5328 Column 3:
5329 column_name = hire_date
5330 type = 10 (DATE)
5331 null_ok = 0
5332 column_flags = 4225
5333 </pre><p>
5334 The <code class="literal">column_flags</code> value is an instance of the
5335 <code class="literal">constants.FieldFlag</code> class. To see how to
5336 interpret it, do this:
5337 </p><pre data-lang="python" class="programlisting">&gt;&gt;&gt; from mysql.connector import FieldFlag
5338 &gt;&gt;&gt; FieldFlag.desc
5339 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-warnings"></a>10.5.18 MySQLCursor.warnings Property</h3></div></div></div><a class="indexterm" name="id4742"></a><a class="indexterm" name="id4744"></a><p>
5340 Syntax:
5341 </p><pre data-lang="python" class="programlisting">tuples = cursor.warnings
5342 </pre><p>
5343 This property returns a list of tuples containing warnings
5344 generated by the previously executed operation. To set whether
5345 to fetch warnings, use the connection's
5346 <a class="link" href="#connector-python-api-mysqlconnection-get-warnings" title="10.2.45 MySQLConnection.get_warnings Property"><code class="literal">get_warnings</code></a>
5347 property.
5348 </p><p>
5349 The following example shows a
5350 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a> statement that generates a
5351 warning:
5352 </p><pre data-lang="python" class="programlisting">&gt;&gt;&gt; cnx.get_warnings = True
5353 &gt;&gt;&gt; cursor.execute("SELECT 'a'+1")
5354 &gt;&gt;&gt; cursor.fetchall()
5355 [(1.0,)]
5356 &gt;&gt;&gt; print(cursor.warnings)
5357 [(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]
5358 </pre><p>
5359 When warnings are generated, it is possible to raise errors
5360 instead, using the connection's
5361 <a class="link" href="#connector-python-api-mysqlconnection-raise-on-warnings" title="10.2.47 MySQLConnection.raise_on_warnings Property"><code class="literal">raise_on_warnings</code></a>
5362 property.
5363 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-lastrowid"></a>10.5.19 MySQLCursor.lastrowid Property</h3></div></div></div><a class="indexterm" name="id4760"></a><a class="indexterm" name="id4762"></a><p>
5364 Syntax:
5365 </p><pre data-lang="python" class="programlisting">id = cursor.lastrowid
5366 </pre><p>
5367 This read-only property returns the value generated for an
5368 <code class="literal">AUTO_INCREMENT</code> column by the previous
5369 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a> or
5370 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a> statement or
5371 <code class="literal">None</code> when there is no such value available.
5372 For example, if you perform an
5373 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a> into a table that contains
5374 an <code class="literal">AUTO_INCREMENT</code> column,
5375 <code class="literal">lastrowid</code> returns the
5376 <code class="literal">AUTO_INCREMENT</code> value for the new row. For an
5377 example, see
5378 <a class="xref" href="#connector-python-example-cursor-transaction" title="5.3 Inserting Data Using Connector/Python">Section 5.3, “Inserting Data Using Connector/Python”</a>.
5379 </p><p>
5380 The <code class="literal">lastrowid</code> property is like the
5381 <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-insert-id.html" target="_top"><code class="literal">mysql_insert_id()</code></a> C API
5382 function; see <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-insert-id.html" target="_top">mysql_insert_id()</a>.
5383 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-rowcount"></a>10.5.20 MySQLCursor.rowcount Property</h3></div></div></div><a class="indexterm" name="id4786"></a><a class="indexterm" name="id4788"></a><p>
5384 Syntax:
5385 </p><pre data-lang="python" class="programlisting">count = cursor.rowcount
5386 </pre><p>
5387 This read-only property returns the number of rows returned for
5388 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a> statements, or the number
5389 of rows affected by DML statements such as
5390 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a> or
5391 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a>. For an example, see
5392 <a class="xref" href="#connector-python-api-mysqlcursor-execute" title="10.5.7 MySQLCursor.execute() Method">Section 10.5.7, “MySQLCursor.execute() Method”</a>.
5393 </p><p>
5394 For nonbuffered cursors, the row count cannot be known before
5395 the rows have been fetched. In this case, the number of rows is
5396 -1 immediately after query execution and is incremented as rows
5397 are fetched.
5398 </p><p>
5399 The <code class="literal">rowcount</code> property is like the
5400 <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-affected-rows.html" target="_top"><code class="literal">mysql_affected_rows()</code></a> C API
5401 function; see <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-affected-rows.html" target="_top">mysql_affected_rows()</a>.
5402 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-statement"></a>10.5.21 MySQLCursor.statement Property</h3></div></div></div><a class="indexterm" name="id4808"></a><a class="indexterm" name="id4810"></a><p>
5403 Syntax:
5404 </p><pre data-lang="python" class="programlisting">str = cursor.statement
5405 </pre><p>
5406 This read-only property returns the last executed statement as a
5407 string. The <code class="literal">statement</code> property can be useful
5408 for debugging and displaying what was sent to the MySQL server.
5409 </p><p>
5410 The string can contain multiple statements if a
5411 multiple-statement string was executed. This occurs for
5412 <code class="literal">execute()</code> with <code class="literal">multi=True</code>.
5413 In this case, the <code class="literal">statement</code> property contains
5414 the entire statement string and the <code class="literal">execute()</code>
5415 call returns an iterator that can be used to process results
5416 from the individual statements. The <code class="literal">statement</code>
5417 property for this iterator shows statement strings for the
5418 individual statements.
5419 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-with-rows"></a>10.5.22 MySQLCursor.with_rows Property</h3></div></div></div><a class="indexterm" name="id4824"></a><a class="indexterm" name="id4826"></a><p>
5420 Syntax:
5421 </p><pre data-lang="python" class="programlisting">boolean = cursor.with_rows
5422 </pre><p>
5423 This read-only property returns <code class="literal">True</code> or
5424 <code class="literal">False</code> to indicate whether the most recently
5425 executed operation could have produced rows.
5426 </p><p>
5427 The <code class="literal">with_rows</code> property is useful when it is
5428 necessary to determine whether a statement produces a result set
5429 and you need to fetch rows. The following example retrieves the
5430 rows returned by the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a>
5431 statements, but reports only the affected-rows value for the
5432 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a> statement:
5433 </p><pre data-lang="python" class="programlisting">import mysql.connector
5434
5435 cnx = mysql.connector.connect(user='scott', database='test')
5436 cursor = cnx.cursor()
5437 operation = 'SELECT 1; UPDATE t1 SET c1 = 2; SELECT 2'
5438 for result in cursor.execute(operation):
5439 if result.with_rows:
5440 result.fetchall()
5441 else:
5442 print("Number of affected rows: {}".format(result.rowcount))
5443 </pre></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cursor-subclasses"></a>10.6 Subclasses cursor.MySQLCursor</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffered">10.6.1 cursor.MySQLCursorBuffered Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorraw">10.6.2 cursor.MySQLCursorRaw Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursordict">10.6.3 cursor.MySQLCursorDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffereddict">10.6.4 cursor.MySQLCursorBufferedDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorprepared">10.6.5 cursor.MySQLCursorPrepared Class</a></span></dt></dl></div><a class="indexterm" name="id4842"></a><a class="indexterm" name="id4844"></a><p>
5444 The cursor classes described in the following sections inherit
5445 from the <code class="literal">MySQLCursor</code> class, which is described
5446 in <a class="xref" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">Section 10.5, “cursor.MySQLCursor Class”</a>.
5447 </p><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursorbuffered"></a>10.6.1 cursor.MySQLCursorBuffered Class</h3></div></div></div><a class="indexterm" name="id4851"></a><a class="indexterm" name="id4853"></a><p>
5448 The <code class="literal">MySQLCursorBuffered</code> class inherits from
5449 <a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class"><code class="literal">MySQLCursor</code></a>.
5450 </p><p>
5451 After executing a query, a
5452 <code class="literal">MySQLCursorBuffered</code> cursor fetches the entire
5453 result set from the server and buffers the rows.
5454 </p><p>
5455 For queries executed using a buffered cursor, row-fetching
5456 methods such as
5457 <a class="link" href="#connector-python-api-mysqlcursor-fetchone" title="10.5.11 MySQLCursor.fetchone() Method"><code class="literal">fetchone()</code></a>
5458 return rows from the set of buffered rows. For nonbuffered
5459 cursors, rows are not fetched from the server until a
5460 row-fetching method is called. In this case, you must be sure to
5461 fetch all rows of the result set before executing any other
5462 statements on the same connection, or an
5463 <code class="literal">InternalError</code> (Unread result found) exception
5464 will be raised.
5465 </p><p>
5466 <code class="literal">MySQLCursorBuffered</code> can be useful in
5467 situations where multiple queries, with small result sets, need
5468 to be combined or computed with each other.
5469 </p><p>
5470 To create a buffered cursor, use the <code class="literal">buffered</code>
5471 argument when calling a connection's
5472 <a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
5473 method. Alternatively, to make all cursors created from the
5474 connection buffered by default, use the
5475 <code class="literal">buffered</code>
5476 <a class="link" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">connection
5477 argument</a>.
5478 </p><p>
5479 Example:
5480 </p><pre data-lang="python" class="programlisting">import mysql.connector
5481
5482 cnx = mysql.connector.connect()
5483
5484 # Only this particular cursor will buffer results
5485 cursor = cnx.cursor(buffered=True)
5486
5487 # All cursors created from cnx2 will be buffered by default
5488 cnx2 = mysql.connector.connect(buffered=True)
5489 </pre><p>
5490 For a practical use case, see
5491 <a class="xref" href="#connector-python-tutorial-cursorbuffered" title="6.1 Tutorial: Raise Employee's Salary Using a Buffered Cursor">Section 6.1, “Tutorial: Raise Employee's Salary Using a Buffered Cursor”</a>.
5492 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursorraw"></a>10.6.2 cursor.MySQLCursorRaw Class</h3></div></div></div><a class="indexterm" name="id4879"></a><a class="indexterm" name="id4881"></a><p>
5493 The <code class="literal">MySQLCursorRaw</code> class inherits from
5494 <a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class"><code class="literal">MySQLCursor</code></a>.
5495 </p><p>
5496 A <code class="literal">MySQLCursorRaw</code> cursor skips the conversion
5497 from MySQL data types to Python types when fetching rows. A raw
5498 cursor is usually used to get better performance or when you
5499 want to do the conversion yourself.
5500 </p><p>
5501 To create a raw cursor, use the <code class="literal">raw</code> argument
5502 when calling a connection's
5503 <a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
5504 method. Alternatively, to make all cursors created from the
5505 connection raw by default, use the <code class="literal">raw</code>
5506 <a class="link" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">connection
5507 argument</a>.
5508 </p><p>
5509 Example:
5510 </p><pre data-lang="python" class="programlisting">import mysql.connector
5511
5512 cnx = mysql.connector.connect()
5513
5514 # Only this particular cursor will be raw
5515 cursor = cnx.cursor(raw=True)
5516
5517 # All cursors created from cnx2 will be raw by default
5518 cnx2 = mysql.connector.connect(raw=True)
5519 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursordict"></a>10.6.3 cursor.MySQLCursorDict Class</h3></div></div></div><a class="indexterm" name="id4899"></a><a class="indexterm" name="id4901"></a><p>
5520 The <code class="literal">MySQLCursorDict</code> class inherits from
5521 <a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class"><code class="literal">MySQLCursor</code></a>.
5522 This class is available as of Connector/Python 2.0.0.
5523 </p><p>
5524 A <code class="literal">MySQLCursorDict</code> cursor returns each row as
5525 a dictionary. The keys for each dictionary object are the column
5526 names of the MySQL result.
5527 </p><p>
5528 Example:
5529 </p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(database='world')
5530 cursor = cnx.cursor(dictionary=True)
5531 cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")
5532
5533 print("Countries in Europe:")
5534 for row in cursor:
5535 print("* {Name}".format(Name=row['Name']
5536 </pre><p>
5537 The preceding code produces output like this:
5538 </p><pre data-lang="none" class="programlisting">Countries in Europe:
5539 * Albania
5540 * Andorra
5541 * Austria
5542 * Belgium
5543 * Bulgaria
5544 ...
5545 </pre><p>
5546 It may be convenient to pass the dictionary to
5547 <code class="literal">format()</code> as follows:
5548 </p><pre data-lang="python" class="programlisting">cursor.execute("SELECT Name, Population FROM country WHERE Continent = 'Europe'")
5549
5550 print("Countries in Europe with population:")
5551 for row in cursor:
5552 print("* {Name}: {Population}".format(**row))
5553 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursorbuffereddict"></a>10.6.4 cursor.MySQLCursorBufferedDict Class</h3></div></div></div><a class="indexterm" name="id4918"></a><a class="indexterm" name="id4920"></a><p>
5554 The <code class="literal">MySQLCursorBufferedDict</code> class inherits
5555 from
5556 <a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class"><code class="literal">MySQLCursor</code></a>.
5557 This class is available as of Connector/Python 2.0.0.
5558 </p><p>
5559 A <code class="literal">MySQLCursorBufferedDict</code> cursor is like a
5560 <a class="link" href="#connector-python-api-mysqlcursordict" title="10.6.3 cursor.MySQLCursorDict Class"><code class="literal">MySQLCursorDict</code></a>
5561 cursor, but is buffered: After executing a query, it fetches the
5562 entire result set from the server and buffers the rows. For
5563 information about the implications of buffering, see
5564 <a class="xref" href="#connector-python-api-mysqlcursorbuffered" title="10.6.1 cursor.MySQLCursorBuffered Class">Section 10.6.1, “cursor.MySQLCursorBuffered Class”</a>.
5565 </p><p>
5566 To get a buffered cursor that returns dictionaries, add the
5567 <code class="literal">buffered</code> argument when instantiating a new
5568 dictionary cursor:
5569 </p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(dictionary=True, buffered=True)
5570 </pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursorprepared"></a>10.6.5 cursor.MySQLCursorPrepared Class</h3></div></div></div><a class="indexterm" name="id4936"></a><a class="indexterm" name="id4938"></a><a class="indexterm" name="id4941"></a><p>
5571 The <code class="literal">MySQLCursorPrepared</code> class inherits from
5572 <a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class"><code class="literal">MySQLCursor</code></a>.
5573 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
5574 This class is available as of Connector/Python 1.1.0. The C extension
5575 supports it as of Connector/Python 8.0.17.
5576 </p></div><p>
5577 In MySQL, there are two ways to execute a prepared statement:
5578 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
5579 Use the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/prepare.html" target="_top"><code class="literal">PREPARE</code></a> and
5580 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/execute.html" target="_top"><code class="literal">EXECUTE</code></a> statements.
5581 </p></li><li class="listitem"><p>
5582 Use the binary client/server protocol to send and receive
5583 data. To repeatedly execute the same statement with
5584 different data for different executions, this is more
5585 efficient than using <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/prepare.html" target="_top"><code class="literal">PREPARE</code></a>
5586 and <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/execute.html" target="_top"><code class="literal">EXECUTE</code></a>. For information
5587 about the binary protocol, see
5588 <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/c-api-prepared-statement-interface.html" target="_top">C API Prepared Statement Interface</a>.
5589 </p></li></ul></div><p>
5590 In Connector/Python, there are two ways to create a cursor that enables
5591 execution of prepared statements using the binary protocol. In
5592 both cases, the <code class="literal">cursor()</code> method of the
5593 connection object returns a
5594 <code class="literal">MySQLCursorPrepared</code> object:
5595 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
5596 The simpler syntax uses a <code class="literal">prepared=True</code>
5597 argument to the <code class="literal">cursor()</code> method. This
5598 syntax is available as of Connector/Python 1.1.2.
5599 </p><pre data-lang="python" class="programlisting">import mysql.connector
5600
5601 cnx = mysql.connector.connect(database='employees')
5602 cursor = cnx.cursor(prepared=True)
5603 </pre></li><li class="listitem"><p>
5604 Alternatively, create an instance of the
5605 <code class="literal">MySQLCursorPrepared</code> class using the
5606 <code class="literal">cursor_class</code> argument to the
5607 <code class="literal">cursor()</code> method. This syntax is available
5608 as of Connector/Python 1.1.0.
5609 </p><pre data-lang="python" class="programlisting">import mysql.connector
5610 from mysql.connector.cursor import MySQLCursorPrepared
5611
5612 cnx = mysql.connector.connect(database='employees')
5613 cursor = cnx.cursor(cursor_class=MySQLCursorPrepared)
5614 </pre></li></ul></div><p>
5615 A cursor instantiated from the
5616 <code class="literal">MySQLCursorPrepared</code> class works like this:
5617 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
5618 The first time you pass a statement to the cursor's
5619 <code class="literal">execute()</code> method, it prepares the
5620 statement. For subsequent invocations of
5621 <code class="literal">execute()</code>, the preparation phase is
5622 skipped if the statement is the same.
5623 </p></li><li class="listitem"><p>
5624 The <code class="literal">execute()</code> method takes an optional
5625 second argument containing a list of data values to
5626 associate with parameter markers in the statement. If the
5627 list argument is present, there must be one value per
5628 parameter marker.
5629 </p></li></ul></div><p>
5630 Example:
5631 </p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(prepared=True)
5632 stmt = "SELECT fullname FROM employees WHERE id = %s" # (1)
5633 cursor.execute(stmt, (5,)) # (2)
5634 # ... fetch data ...
5635 cursor.execute(stmt, (10,)) # (3)
5636 # ... fetch data ...
5637 </pre><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
5638 The <code class="literal">%s</code> within the statement is a
5639 parameter marker. Do not put quote marks around parameter
5640 markers.
5641 </p></li><li class="listitem"><p>
5642 For the first call to the <code class="literal">execute()</code>
5643 method, the cursor prepares the statement. If data is given
5644 in the same call, it also executes the statement and you
5645 should fetch the data.
5646 </p></li><li class="listitem"><p>
5647 For subsequent <code class="literal">execute()</code> calls that pass
5648 the same SQL statement, the cursor skips the preparation
5649 phase.
5650 </p></li></ol></div><p>
5651 Prepared statements executed with
5652 <code class="literal">MySQLCursorPrepared</code> can use the
5653 <code class="literal">format</code> (<code class="literal">%s</code>) or
5654 <code class="literal">qmark</code> (<code class="literal">?</code>) parameterization
5655 style. This differs from nonprepared statements executed with
5656 <code class="literal">MySQLCursor</code>, which can use the
5657 <code class="literal">format</code> or <code class="literal">pyformat</code>
5658 parameterization style.
5659 </p><p>
5660 To use multiple prepared statements simultaneously, instantiate
5661 multiple cursors from the <code class="literal">MySQLCursorPrepared</code>
5662 class.
5663 </p><a class="indexterm" name="id5012"></a><p>
5664 The MySQL client/server protocol has an option to send prepared
5665 statement parameters via the
5666 <code class="literal">COM_STMT_SEND_LONG_DATA</code> command. To use this
5667 from Connector/Python scripts, send the parameter in question using the
5668 <code class="literal">IOBase</code> interface. Example:
5669 </p><pre data-lang="python" class="programlisting">from io import IOBase
5670
5671 ...
5672
5673 cur = cnx.cursor(prepared=True)
5674 cur.execute("SELECT (%s)", (io.BytesIO(bytes("A", "latin1")), ))
5675 </pre></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-clientflag"></a>10.7 constants.ClientFlag Class</h2></div></div></div><a class="indexterm" name="id5020"></a><a class="indexterm" name="id5022"></a><p>
5676 This class provides constants defining MySQL client flags that can
5677 be used when the connection is established to configure the
5678 session. The <code class="literal">ClientFlag</code> class is available when
5679 importing <code class="literal">mysql.connector</code>.
5680 </p><pre data-lang="python" class="programlisting">
5681 &gt;&gt;&gt; import mysql.connector
5682 &gt;&gt;&gt; mysql.connector.ClientFlag.FOUND_ROWS
5683 2</pre><p>
5684 See
5685 <a class="xref" href="#connector-python-api-mysqlconnection-set-client-flags" title="10.2.32 MySQLConnection.set_client_flags() Method">Section 10.2.32, “MySQLConnection.set_client_flags() Method”</a>
5686 and the <a class="link" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">connection
5687 argument</a> <code class="literal">client_flag</code>.
5688 </p><p>
5689 The <code class="literal">ClientFlag</code> class cannot be instantiated.
5690 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-fieldtype"></a>10.8 constants.FieldType Class</h2></div></div></div><a class="indexterm" name="id5036"></a><a class="indexterm" name="id5038"></a><p>
5691 This class provides all supported MySQL field or data types. They
5692 can be useful when dealing with raw data or defining your own
5693 converters. The field type is stored with every cursor in the
5694 description for each column.
5695 </p><p>
5696 The following example shows how to print the name of the data type
5697 for each column in a result set.
5698 </p><pre data-lang="python" class="programlisting">from __future__ import print_function
5699 import mysql.connector
5700 from mysql.connector import FieldType
5701
5702 cnx = mysql.connector.connect(user='scott', database='test')
5703 cursor = cnx.cursor()
5704
5705 cursor.execute(
5706 "SELECT DATE(NOW()) AS `c1`, TIME(NOW()) AS `c2`, "
5707 "NOW() AS `c3`, 'a string' AS `c4`, 42 AS `c5`")
5708 rows = cursor.fetchall()
5709
5710 for desc in cursor.description:
5711 colname = desc[0]
5712 coltype = desc[1]
5713 print("Column {} has type {}".format(
5714 colname, FieldType.get_info(coltype)))
5715
5716 cursor.close()
5717 cnx.close()
5718 </pre><p>
5719 The <code class="literal">FieldType</code> class cannot be instantiated.
5720 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-sqlmode"></a>10.9 constants.SQLMode Class</h2></div></div></div><a class="indexterm" name="id5047"></a><a class="indexterm" name="id5049"></a><p>
5721 This class provides all known MySQL
5722 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html" target="_top">Server SQL Modes</a>. It is mostly
5723 used when setting the SQL modes at connection time using the
5724 connection's <code class="literal">sql_mode</code> property. See
5725 <a class="xref" href="#connector-python-api-mysqlconnection-sql-mode" title="10.2.52 MySQLConnection.sql_mode Property">Section 10.2.52, “MySQLConnection.sql_mode Property”</a>.
5726 </p><p>
5727 The <code class="literal">SQLMode</code> class cannot be instantiated.
5728 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-characterset"></a>10.10 constants.CharacterSet Class</h2></div></div></div><a class="indexterm" name="id5059"></a><a class="indexterm" name="id5061"></a><p>
5729 This class provides all known MySQL characters sets and their
5730 default collations. For examples, see
5731 <a class="xref" href="#connector-python-api-mysqlconnection-set-charset-collation" title="10.2.31 MySQLConnection.set_charset_collation() Method">Section 10.2.31, “MySQLConnection.set_charset_collation() Method”</a>.
5732 </p><p>
5733 The <code class="literal">CharacterSet</code> class cannot be instantiated.
5734 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-refreshoption"></a>10.11 constants.RefreshOption Class</h2></div></div></div><a class="indexterm" name="id5069"></a><a class="indexterm" name="id5071"></a><p>
5735 This class performs various flush operations.
5736 </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
5737 <code class="literal">RefreshOption.GRANT</code>
5738 </p><p>
5739 Refresh the grant tables, like <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-privileges" target="_top"><code class="literal">FLUSH
5740 PRIVILEGES</code></a>.
5741 </p></li><li class="listitem"><p>
5742 <code class="literal">RefreshOption.LOG</code>
5743 </p><p>
5744 Flush the logs, like <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-logs" target="_top"><code class="literal">FLUSH
5745 LOGS</code></a>.
5746 </p></li><li class="listitem"><p>
5747 <code class="literal">RefreshOption.TABLES</code>
5748 </p><p>
5749 Flush the table cache, like <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-tables" target="_top"><code class="literal">FLUSH
5750 TABLES</code></a>.
5751 </p></li><li class="listitem"><p>
5752 <code class="literal">RefreshOption.HOSTS</code>
5753 </p><p>
5754 Flush the host cache, like <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-hosts" target="_top"><code class="literal">FLUSH
5755 HOSTS</code></a>.
5756 </p></li><li class="listitem"><p>
5757 <code class="literal">RefreshOption.STATUS</code>
5758 </p><p>
5759 Reset status variables, like <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-status" target="_top"><code class="literal">FLUSH
5760 STATUS</code></a>.
5761 </p></li><li class="listitem"><p>
5762 <code class="literal">RefreshOption.THREADS</code>
5763 </p><p>
5764 Flush the thread cache.
5765 </p></li><li class="listitem"><p>
5766 <code class="literal">RefreshOption.REPLICA</code>
5767 </p><p>
5768 On a replica replication server, reset the source server
5769 information and restart the replica, like
5770 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/reset-slave.html" target="_top"><code class="literal">RESET SLAVE</code></a>. This constant was
5771 named "RefreshOption.SLAVE" before v8.0.23.
5772 </p></li></ul></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-errors"></a>10.12 Errors and Exceptions</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-errorcode">10.12.1 errorcode Module</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-error">10.12.2 errors.Error Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-dataerror">10.12.3 errors.DataError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-databaseerror">10.12.4 errors.DatabaseError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-integrityerror">10.12.5 errors.IntegrityError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-interfaceerror">10.12.6 errors.InterfaceError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-internalerror">10.12.7 errors.InternalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-notsupportederror">10.12.8 errors.NotSupportedError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-operationalerror">10.12.9 errors.OperationalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-poolerror">10.12.10 errors.PoolError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-programmingerror">10.12.11 errors.ProgrammingError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-warning">10.12.12 errors.Warning Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-custom-error-exception">10.12.13 errors.custom_error_exception() Function</a></span></dt></dl></div><p>
5773 The <code class="literal">mysql.connector.errors</code> module defines
5774 exception classes for errors and warnings raised by MySQL Connector/Python. Most
5775 classes defined in this module are available when you import
5776 <code class="literal">mysql.connector</code>.
5777 </p><p>
5778 The exception classes defined in this module mostly follow the
5779 Python Database API Specification v2.0 (PEP 249). For some MySQL
5780 client or server errors it is not always clear which exception to
5781 raise. It is good to discuss whether an error should be
5782 reclassified by opening a bug report.
5783 </p><p>
5784 MySQL Server errors are mapped with Python exception based on
5785 their SQLSTATE value (see
5786 <a class="ulink" href="https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html" target="_top">Server Error Message Reference</a>). The following table
5787 shows the SQLSTATE classes and the exception Connector/Python raises. It is,
5788 however, possible to redefine which exception is raised for each
5789 server error. The default exception is
5790 <code class="literal">DatabaseError</code>.
5791 </p><div class="table"><a name="connector-python-api-errors-exceptions-map"></a><p class="title"><b>Table 10.1 Mapping of Server Errors to Python Exceptions</b></p><div class="table-contents"><table><col width="40%"><col width="60%"><thead><tr>
5792 <th scope="col">SQLSTATE Class</th>
5793 <th scope="col">Connector/Python Exception</th>
5794 </tr></thead><tbody><tr>
5795 <td><code class="literal">02</code></td>
5796 <td><code class="literal">DataError</code></td>
5797 </tr><tr>
5798 <td><code class="literal">02</code></td>
5799 <td><code class="literal">DataError</code></td>
5800 </tr><tr>
5801 <td><code class="literal">07</code></td>
5802 <td><code class="literal">DatabaseError</code></td>
5803 </tr><tr>
5804 <td><code class="literal">08</code></td>
5805 <td><code class="literal">OperationalError</code></td>
5806 </tr><tr>
5807 <td><code class="literal">0A</code></td>
5808 <td><code class="literal">NotSupportedError</code></td>
5809 </tr><tr>
5810 <td><code class="literal">21</code></td>
5811 <td><code class="literal">DataError</code></td>
5812 </tr><tr>
5813 <td><code class="literal">22</code></td>
5814 <td><code class="literal">DataError</code></td>
5815 </tr><tr>
5816 <td><code class="literal">23</code></td>
5817 <td><code class="literal">IntegrityError</code></td>
5818 </tr><tr>
5819 <td><code class="literal">24</code></td>
5820 <td><code class="literal">ProgrammingError</code></td>
5821 </tr><tr>
5822 <td><code class="literal">25</code></td>
5823 <td><code class="literal">ProgrammingError</code></td>
5824 </tr><tr>
5825 <td><code class="literal">26</code></td>
5826 <td><code class="literal">ProgrammingError</code></td>
5827 </tr><tr>
5828 <td><code class="literal">27</code></td>
5829 <td><code class="literal">ProgrammingError</code></td>
5830 </tr><tr>
5831 <td><code class="literal">28</code></td>
5832 <td><code class="literal">ProgrammingError</code></td>
5833 </tr><tr>
5834 <td><code class="literal">2A</code></td>
5835 <td><code class="literal">ProgrammingError</code></td>
5836 </tr><tr>
5837 <td><code class="literal">2B</code></td>
5838 <td><code class="literal">DatabaseError</code></td>
5839 </tr><tr>
5840 <td><code class="literal">2C</code></td>
5841 <td><code class="literal">ProgrammingError</code></td>
5842 </tr><tr>
5843 <td><code class="literal">2D</code></td>
5844 <td><code class="literal">DatabaseError</code></td>
5845 </tr><tr>
5846 <td><code class="literal">2E</code></td>
5847 <td><code class="literal">DatabaseError</code></td>
5848 </tr><tr>
5849 <td><code class="literal">33</code></td>
5850 <td><code class="literal">DatabaseError</code></td>
5851 </tr><tr>
5852 <td><code class="literal">34</code></td>
5853 <td><code class="literal">ProgrammingError</code></td>
5854 </tr><tr>
5855 <td><code class="literal">35</code></td>
5856 <td><code class="literal">ProgrammingError</code></td>
5857 </tr><tr>
5858 <td><code class="literal">37</code></td>
5859 <td><code class="literal">ProgrammingError</code></td>
5860 </tr><tr>
5861 <td><code class="literal">3C</code></td>
5862 <td><code class="literal">ProgrammingError</code></td>
5863 </tr><tr>
5864 <td><code class="literal">3D</code></td>
5865 <td><code class="literal">ProgrammingError</code></td>
5866 </tr><tr>
5867 <td><code class="literal">3F</code></td>
5868 <td><code class="literal">ProgrammingError</code></td>
5869 </tr><tr>
5870 <td><code class="literal">40</code></td>
5871 <td><code class="literal">InternalError</code></td>
5872 </tr><tr>
5873 <td><code class="literal">42</code></td>
5874 <td><code class="literal">ProgrammingError</code></td>
5875 </tr><tr>
5876 <td><code class="literal">44</code></td>
5877 <td><code class="literal">InternalError</code></td>
5878 </tr><tr>
5879 <td><code class="literal">HZ</code></td>
5880 <td><code class="literal">OperationalError</code></td>
5881 </tr><tr>
5882 <td><code class="literal">XA</code></td>
5883 <td><code class="literal">IntegrityError</code></td>
5884 </tr><tr>
5885 <td><code class="literal">0K</code></td>
5886 <td><code class="literal">OperationalError</code></td>
5887 </tr><tr>
5888 <td><code class="literal">HY</code></td>
5889 <td><code class="literal">DatabaseError</code></td>
5890 </tr></tbody></table></div></div><br class="table-break"><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errorcode"></a>10.12.1 errorcode Module</h3></div></div></div><a class="indexterm" name="id5295"></a><a class="indexterm" name="id5297"></a><p>
5891 This module contains both MySQL server and client error codes
5892 defined as module attributes with the error number as value.
5893 Using error codes instead of error numbers could make reading
5894 the source code a bit easier.
5895 </p><pre data-lang="python" class="programlisting">
5896 &gt;&gt;&gt; from mysql.connector import errorcode
5897 &gt;&gt;&gt; errorcode.ER_BAD_TABLE_ERROR
5898 1051</pre><p>
5899 For more information about MySQL errors, see
5900 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/error-handling.html" target="_top">Error Messages and Common Problems</a>.
5901 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-error"></a>10.12.2 errors.Error Exception</h3></div></div></div><a class="indexterm" name="id5305"></a><a class="indexterm" name="id5307"></a><p>
5902 This exception is the base class for all other exceptions in the
5903 <code class="literal">errors</code> module. It can be used to catch all
5904 errors in a single <code class="literal">except</code> statement.
5905 </p><p>
5906 The following example shows how we could catch syntax errors:
5907 </p><pre data-lang="python" class="programlisting">import mysql.connector
5908
5909 try:
5910 cnx = mysql.connector.connect(user='scott', database='employees')
5911 cursor = cnx.cursor()
5912 cursor.execute("SELECT * FORM employees") # Syntax error in query
5913 cnx.close()
5914 except mysql.connector.Error as err:
5915 print("Something went wrong: {}".format(err))
5916 </pre><p>
5917 Initializing the exception supports a few optional arguments,
5918 namely <code class="literal">msg</code>, <code class="literal">errno</code>,
5919 <code class="literal">values</code> and <code class="literal">sqlstate</code>. All
5920 of them are optional and default to <code class="literal">None</code>.
5921 <code class="literal">errors.Error</code> is internally used by Connector/Python to
5922 raise MySQL client and server errors and should not be used by
5923 your application to raise exceptions.
5924 </p><p>
5925 The following examples show the result when using no arguments
5926 or a combination of the arguments:
5927 </p><pre data-lang="python" class="programlisting">
5928 &gt;&gt;&gt; from mysql.connector.errors import Error
5929 &gt;&gt;&gt; str(Error())
5930 'Unknown error'
5931
5932 &gt;&gt;&gt; str(Error("Oops! There was an error."))
5933 'Oops! There was an error.'
5934
5935 &gt;&gt;&gt; str(Error(errno=2006))
5936 '2006: MySQL server has gone away'
5937
5938 &gt;&gt;&gt; str(Error(errno=2002, values=('/tmp/mysql.sock', 2)))
5939 "2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)"
5940
5941 &gt;&gt;&gt; str(Error(errno=1146, sqlstate='42S02', msg="Table 'test.spam' doesn't exist"))
5942 "1146 (42S02): Table 'test.spam' doesn't exist"</pre><p>
5943 The example which uses error number 1146 is used when Connector/Python
5944 receives an error packet from the MySQL Server. The information
5945 is parsed and passed to the <code class="literal">Error</code> exception
5946 as shown.
5947 </p><p>
5948 Each exception subclassing from <code class="literal">Error</code> can be
5949 initialized using the previously mentioned arguments.
5950 Additionally, each instance has the attributes
5951 <code class="literal">errno</code>, <code class="literal">msg</code> and
5952 <code class="literal">sqlstate</code> which can be used in your code.
5953 </p><p>
5954 The following example shows how to handle errors when dropping a
5955 table which does not exist (when the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/drop-table.html" target="_top"><code class="literal">DROP
5956 TABLE</code></a> statement does not include a <code class="literal">IF
5957 EXISTS</code> clause):
5958 </p><pre data-lang="python" class="programlisting">import mysql.connector
5959 from mysql.connector import errorcode
5960
5961 cnx = mysql.connector.connect(user='scott', database='test')
5962 cursor = cnx.cursor()
5963 try:
5964 cursor.execute("DROP TABLE spam")
5965 except mysql.connector.Error as err:
5966 if err.errno == errorcode.ER_BAD_TABLE_ERROR:
5967 print("Creating table spam")
5968 else:
5969 raise
5970 </pre><p>
5971 Prior to Connector/Python 1.1.1, the original message passed to
5972 <code class="literal">errors.Error()</code> is not saved in such a way
5973 that it could be retrieved. Instead, the
5974 <code class="literal">Error.msg</code> attribute was formatted with the
5975 error number and SQLSTATE value. As of 1.1.1, only the original
5976 message is saved in the <code class="literal">Error.msg</code> attribute.
5977 The formatted value together with the error number and SQLSTATE
5978 value can be obtained by printing or getting the string
5979 representation of the error object. Example:
5980 </p><pre data-lang="python" class="programlisting">try:
5981 conn = mysql.connector.connect(database = "baddb")
5982 except mysql.connector.Error as e:
5983 print "Error code:", e.errno # error number
5984 print "SQLSTATE value:", e.sqlstate # SQLSTATE value
5985 print "Error message:", e.msg # error message
5986 print "Error:", e # errno, sqlstate, msg values
5987 s = str(e)
5988 print "Error:", s # errno, sqlstate, msg values
5989 </pre><p>
5990 <code class="literal">errors.Error</code> is a subclass of the Python
5991 <code class="literal">StandardError</code>.
5992 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-dataerror"></a>10.12.3 errors.DataError Exception</h3></div></div></div><a class="indexterm" name="id5345"></a><a class="indexterm" name="id5347"></a><p>
5993 This exception is raised when there were problems with the data.
5994 Examples are a column set to <code class="literal">NULL</code> that cannot
5995 be <code class="literal">NULL</code>, out-of-range values for a column,
5996 division by zero, column count does not match value count, and
5997 so on.
5998 </p><p>
5999 <code class="literal">errors.DataError</code> is a subclass of
6000 <code class="literal">errors.DatabaseError</code>.
6001 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-databaseerror"></a>10.12.4 errors.DatabaseError Exception</h3></div></div></div><a class="indexterm" name="id5357"></a><a class="indexterm" name="id5359"></a><p>
6002 This exception is the default for any MySQL error which does not
6003 fit the other exceptions.
6004 </p><p>
6005 <code class="literal">errors.DatabaseError</code> is a subclass of
6006 <code class="literal">errors.Error</code>.
6007 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-integrityerror"></a>10.12.5 errors.IntegrityError Exception</h3></div></div></div><a class="indexterm" name="id5367"></a><a class="indexterm" name="id5369"></a><p>
6008 This exception is raised when the relational integrity of the
6009 data is affected. For example, a duplicate key was inserted or a
6010 foreign key constraint would fail.
6011 </p><p>
6012 The following example shows a duplicate key error raised as
6013 IntegrityError:
6014 </p><pre data-lang="python" class="programlisting">cursor.execute("CREATE TABLE t1 (id int, PRIMARY KEY (id))")
6015 try:
6016 cursor.execute("INSERT INTO t1 (id) VALUES (1)")
6017 cursor.execute("INSERT INTO t1 (id) VALUES (1)")
6018 except mysql.connector.IntegrityError as err:
6019 print("Error: {}".format(err))
6020 </pre><p>
6021 <code class="literal">errors.IntegrityError</code> is a subclass of
6022 <code class="literal">errors.DatabaseError</code>.
6023 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-interfaceerror"></a>10.12.6 errors.InterfaceError Exception</h3></div></div></div><a class="indexterm" name="id5379"></a><a class="indexterm" name="id5381"></a><p>
6024 This exception is raised for errors originating from Connector/Python
6025 itself, not related to the MySQL server.
6026 </p><p>
6027 <code class="literal">errors.InterfaceError</code> is a subclass of
6028 <code class="literal">errors.Error</code>.
6029 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-internalerror"></a>10.12.7 errors.InternalError Exception</h3></div></div></div><a class="indexterm" name="id5389"></a><a class="indexterm" name="id5391"></a><p>
6030 This exception is raised when the MySQL server encounters an
6031 internal error, for example, when a deadlock occurred.
6032 </p><p>
6033 <code class="literal">errors.InternalError</code> is a subclass of
6034 <code class="literal">errors.DatabaseError</code>.
6035 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-notsupportederror"></a>10.12.8 errors.NotSupportedError Exception</h3></div></div></div><a class="indexterm" name="id5399"></a><a class="indexterm" name="id5401"></a><p>
6036 This exception is raised when some feature was used that is not
6037 supported by the version of MySQL that returned the error. It is
6038 also raised when using functions or statements that are not
6039 supported by stored routines.
6040 </p><p>
6041 <code class="literal">errors.NotSupportedError</code> is a subclass of
6042 <code class="literal">errors.DatabaseError</code>.
6043 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-operationalerror"></a>10.12.9 errors.OperationalError Exception</h3></div></div></div><a class="indexterm" name="id5409"></a><a class="indexterm" name="id5411"></a><p>
6044 This exception is raised for errors which are related to MySQL's
6045 operations. For example: too many connections; a host name could
6046 not be resolved; bad handshake; server is shutting down,
6047 communication errors.
6048 </p><p>
6049 <code class="literal">errors.OperationalError</code> is a subclass of
6050 <code class="literal">errors.DatabaseError</code>.
6051 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-poolerror"></a>10.12.10 errors.PoolError Exception</h3></div></div></div><a class="indexterm" name="id5419"></a><a class="indexterm" name="id5421"></a><p>
6052 This exception is raised for connection pool errors.
6053 <code class="literal">errors.PoolError</code> is a subclass of
6054 <code class="literal">errors.Error</code>.
6055 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-programmingerror"></a>10.12.11 errors.ProgrammingError Exception</h3></div></div></div><a class="indexterm" name="id5428"></a><a class="indexterm" name="id5430"></a><p>
6056 This exception is raised on programming errors, for example when
6057 you have a syntax error in your SQL or a table was not found.
6058 </p><p>
6059 The following example shows how to handle syntax errors:
6060 </p><pre data-lang="python" class="programlisting">try:
6061 cursor.execute("CREATE DESK t1 (id int, PRIMARY KEY (id))")
6062 except mysql.connector.ProgrammingError as err:
6063 if err.errno == errorcode.ER_SYNTAX_ERROR:
6064 print("Check your syntax!")
6065 else:
6066 print("Error: {}".format(err))
6067 </pre><p>
6068 <code class="literal">errors.ProgrammingError</code> is a subclass of
6069 <code class="literal">errors.DatabaseError</code>.
6070 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-warning"></a>10.12.12 errors.Warning Exception</h3></div></div></div><a class="indexterm" name="id5440"></a><a class="indexterm" name="id5442"></a><p>
6071 This exception is used for reporting important warnings,
6072 however, Connector/Python does not use it. It is included to be compliant
6073 with the Python Database Specification v2.0 (PEP-249).
6074 </p><p>
6075 Consider using either more strict
6076 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html" target="_top">Server SQL Modes</a> or the
6077 <a class="link" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">raise_on_warnings</a>
6078 connection argument to make Connector/Python raise errors when your queries
6079 produce warnings.
6080 </p><p>
6081 <code class="literal">errors.Warning</code> is a subclass of the Python
6082 <code class="literal">StandardError</code>.
6083 </p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-custom-error-exception"></a>10.12.13 errors.custom_error_exception() Function</h3></div></div></div><a class="indexterm" name="id5453"></a><a class="indexterm" name="id5455"></a><p>
6084 Syntax:
6085 </p><pre data-lang="python" class="programlisting">errors.custom_error_exception(error=None, exception=None)
6086 </pre><p>
6087 This method defines custom exceptions for MySQL server errors
6088 and returns current customizations.
6089 </p><p>
6090 If <code class="literal">error</code> is a MySQL Server error number, you
6091 must also pass the <code class="literal">exception</code> class. The
6092 <code class="literal">error</code> argument can be a dictionary, in which
6093 case the key is the server error number, and value the class of
6094 the exception to be raised.
6095 </p><p>
6096 To reset the customizations, supply an empty dictionary.
6097 </p><pre data-lang="python" class="programlisting">import mysql.connector
6098 from mysql.connector import errorcode
6099
6100 # Server error 1028 should raise a DatabaseError
6101 mysql.connector.custom_error_exception(1028, mysql.connector.DatabaseError)
6102
6103 # Or using a dictionary:
6104 mysql.connector.custom_error_exception({
6105 1028: mysql.connector.DatabaseError,
6106 1029: mysql.connector.OperationalError,
6107 })
6108
6109 # To reset, pass an empty dictionary:
6110 mysql.connector.custom_error_exception({})
6111 </pre></div></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-cext-reference"></a>Chapter 11 Connector/Python C Extension API Reference</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-api-cext-mysql-connector">11.1 _mysql_connector Module</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-mysql">11.2 _mysql_connector.MySQL() Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-affected-rows">11.3 _mysql_connector.MySQL.affected_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-autocommit">11.4 _mysql_connector.MySQL.autocommit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-buffered">11.5 _mysql_connector.MySQL.buffered() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-change-user">11.6 _mysql_connector.MySQL.change_user() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-character-set-name">11.7 _mysql_connector.MySQL.character_set_name() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-close">11.8 _mysql_connector.MySQL.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-commit">11.9 _mysql_connector.MySQL.commit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-connect">11.10 _mysql_connector.MySQL.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-connected">11.11 _mysql_connector.MySQL.connected() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-consume-result">11.12 _mysql_connector.MySQL.consume_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-convert-to-mysql">11.13 _mysql_connector.MySQL.convert_to_mysql() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-escape-string">11.14 _mysql_connector.MySQL.escape_string() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-fetch-fields">11.15 _mysql_connector.MySQL.fetch_fields() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-fetch-row">11.16 _mysql_connector.MySQL.fetch_row() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-field-count">11.17 _mysql_connector.MySQL.field_count() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-free-result">11.18 _mysql_connector.MySQL.free_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-character-set-info">11.19 _mysql_connector.MySQL.get_character_set_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-client-info">11.20 _mysql_connector.MySQL.get_client_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-client-version">11.21 _mysql_connector.MySQL.get_client_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-host-info">11.22 _mysql_connector.MySQL.get_host_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-proto-info">11.23 _mysql_connector.MySQL.get_proto_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-server-info">11.24 _mysql_connector.MySQL.get_server_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-server-version">11.25 _mysql_connector.MySQL.get_server_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-ssl-cipher">11.26 _mysql_connector.MySQL.get_ssl_cipher() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-hex-string">11.27 _mysql_connector.MySQL.hex_string() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-insert-id">11.28 _mysql_connector.MySQL.insert_id() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-more-results">11.29 _mysql_connector.MySQL.more_results() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-next-result">11.30 _mysql_connector.MySQL.next_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-num-fields">11.31 _mysql_connector.MySQL.num_fields() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-num-rows">11.32 _mysql_connector.MySQL.num_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-ping">11.33 _mysql_connector.MySQL.ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-query">11.34 _mysql_connector.MySQL.query() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-raw">11.35 _mysql_connector.MySQL.raw() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-refresh">11.36 _mysql_connector.MySQL.refresh() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-reset-connection">11.37 _mysql_connector.MySQL.reset_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-rollback">11.38 _mysql_connector.MySQL.rollback() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-select-db">11.39 _mysql_connector.MySQL.select_db() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-set-character-set">11.40 _mysql_connector.MySQL.set_character_set() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-shutdown">11.41 _mysql_connector.MySQL.shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-stat">11.42 _mysql_connector.MySQL.stat() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-thread-id">11.43 _mysql_connector.MySQL.thread_id() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-use-unicode">11.44 _mysql_connector.MySQL.use_unicode() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-warning-count">11.45 _mysql_connector.MySQL.warning_count() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-have-result-set">11.46 _mysql_connector.MySQL.have_result_set Property</a></span></dt></dl></div><p>
6112 This chapter contains the public API reference for the Connector/Python C
6113 Extension, also known as the <code class="literal">_mysql_connector</code>
6114 Python module.
6115 </p><p>
6116 The <code class="literal">_mysql_connector</code> C Extension module can be
6117 used directly without any other code of Connector/Python. One reason to use
6118 this module directly is for performance reasons.
6119 </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
6120 Examples in this reference use <code class="literal">ccnx</code> to
6121 represent a connector object as used with the
6122 <code class="literal">_mysql_connector</code> C Extension module.
6123 <code class="literal">ccnx</code> is an instance of the
6124 <code class="literal">_mysql_connector.MySQL()</code> class. It is distinct
6125 from the <code class="literal">cnx</code> object used in examples for the
6126 <code class="literal">mysql.connector</code> Connector/Python module described in
6127 <a class="xref" href="#connector-python-reference" title="Chapter 10 Connector/Python API Reference">Chapter 10, <i>Connector/Python API Reference</i></a>.
6128 <code class="literal">cnx</code> is an instance of the object returned by
6129 the <code class="literal">connect()</code> method of the
6130 <code class="literal">MySQLConnection</code> class.
6131 </p></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
6132 The C Extension is not part of the pure Python installation. It is
6133 an optional module that must be installed using a binary
6134 distribution of Connector/Python that includes it, or compiled using a source
6135 distribution. See <a class="xref" href="#connector-python-installation" title="Chapter 4 Connector/Python Installation">Chapter 4, <i>Connector/Python Installation</i></a>.
6136 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-mysql-connector"></a>11.1 _mysql_connector Module</h2></div></div></div><a class="indexterm" name="id5489"></a><a class="indexterm" name="id5491"></a><p>
6137 The <code class="literal">_mysql_connector</code> module provides classes.
6138 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-mysql"></a>11.2 _mysql_connector.MySQL() Class</h2></div></div></div><a class="indexterm" name="id5497"></a><a class="indexterm" name="id5499"></a><p>
6139 Syntax:
6140 </p><pre data-lang="python" class="programlisting">ccnx = _mysql_connector.MySQL(<em class="replaceable"><code>args</code></em>)
6141 </pre><p>
6142 The <code class="literal">MySQL</code> class is used to open and manage a
6143 connection to a MySQL server (referred to elsewhere in this
6144 reference as <span class="quote">“<span class="quote">the <code class="literal">MySQL</code>
6145 instance</span>”</span>). It is also used to send commands and SQL
6146 statements and read results.
6147 </p><p>
6148 The <code class="literal">MySQL</code> class wraps most functions found in
6149 the MySQL C Client API and adds some additional convenient
6150 functionality.
6151 </p><pre data-lang="python" class="programlisting">import _mysql_connector
6152
6153 ccnx = _mysql_connector.MySQL()
6154 ccnx.connect(user='scott', password='<em class="replaceable"><code>password</code></em>',
6155 host='127.0.0.1', database='employees')
6156 ccnx.close()
6157 </pre><p>
6158 Permitted arguments for the <code class="literal">MySQL</code> class are
6159 <code class="literal">auth_plugin</code>, <code class="literal">buffered</code>,
6160 <code class="literal">charset_name</code>,
6161 <code class="literal">connection_timeout</code>, <code class="literal">raw</code>,
6162 <code class="literal">use_unicode</code>. Those arguments correspond to the
6163 arguments of the same names for
6164 <code class="literal">MySQLConnection.connect()</code> as described at
6165 <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>, except that
6166 <code class="literal">charset_name</code> corresponds to
6167 <code class="literal">charset</code>.
6168 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-affected-rows"></a>11.3 _mysql_connector.MySQL.affected_rows() Method</h2></div></div></div><a class="indexterm" name="id5526"></a><a class="indexterm" name="id5528"></a><p>
6169 Syntax:
6170 </p><pre data-lang="python" class="programlisting">count = ccnx.affected_rows()
6171 </pre><p>
6172 Returns the number of rows changed, inserted, or deleted by the
6173 most recent <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a>,
6174 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a>, or
6175 <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/delete.html" target="_top"><code class="literal">DELETE</code></a> statement.
6176 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-autocommit"></a>11.4 _mysql_connector.MySQL.autocommit() Method</h2></div></div></div><a class="indexterm" name="id5541"></a><a class="indexterm" name="id5543"></a><p>
6177 Syntax:
6178 </p><pre data-lang="python" class="programlisting">ccnx.autocommit(<em class="replaceable"><code>bool</code></em>)
6179 </pre><p>
6180 Sets the autocommit mode.
6181 </p><p>
6182 Raises a <code class="literal">ValueError</code> exception if
6183 <code class="literal">mode</code> is not <code class="literal">True</code> or
6184 <code class="literal">False</code>.
6185 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-buffered"></a>11.5 _mysql_connector.MySQL.buffered() Method</h2></div></div></div><a class="indexterm" name="id5556"></a><a class="indexterm" name="id5558"></a><p>
6186 Syntax:
6187 </p><pre data-lang="python" class="programlisting">is_buffered = ccnx.buffered() # getter
6188 ccnx.buffered(<em class="replaceable"><code>bool</code></em>) # setter
6189 </pre><p>
6190 With no argument, returns <code class="literal">True</code> or
6191 <code class="literal">False</code> to indicate whether the
6192 <code class="literal">MySQL</code> instance buffers (stores) the results.
6193 </p><p>
6194 With a boolean argument, sets the <code class="literal">MySQL</code>
6195 instance buffering mode.
6196 </p><p>
6197 For the setter syntax, raises a <code class="literal">TypeError</code>
6198 exception if the value is not <code class="literal">True</code> or
6199 <code class="literal">False</code>.
6200 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-change-user"></a>11.6 _mysql_connector.MySQL.change_user() Method</h2></div></div></div><a class="indexterm" name="id5575"></a><a class="indexterm" name="id5577"></a><p>
6201 Syntax:
6202 </p><pre data-lang="python" class="programlisting">ccnx.change_user(user='<em class="replaceable"><code>user_name</code></em>,
6203 password='<em class="replaceable"><code>password_val</code></em>',
6204 database='<code class="literal">db_name</code>')
6205 </pre><p>
6206 Changes the user and sets a new default database. Permitted
6207 arguments are <code class="literal">user</code>,
6208 <code class="literal">password</code>, and <code class="literal">database</code>.
6209 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-character-set-name"></a>11.7 _mysql_connector.MySQL.character_set_name() Method</h2></div></div></div><a class="indexterm" name="id5590"></a><a class="indexterm" name="id5592"></a><p>
6210 Syntax:
6211 </p><pre data-lang="python" class="programlisting">charset = ccnx.character_set_name()
6212 </pre><p>
6213 Returns the name of the default character set for the current
6214 MySQL session.
6215 </p><p>
6216 Some MySQL character sets have no equivalent names in Python. When
6217 this is the case, a name usable by Python is returned. For
6218 example, the <code class="literal">'utf8mb4'</code> MySQL character set name
6219 is returned as <code class="literal">'utf8'</code>.
6220 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-close"></a>11.8 _mysql_connector.MySQL.close() Method</h2></div></div></div><a class="indexterm" name="id5602"></a><a class="indexterm" name="id5604"></a><p>
6221 Syntax:
6222 </p><pre data-lang="python" class="programlisting">ccnx.close()
6223 </pre><p>
6224 Closes the MySQL connection.
6225 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-commit"></a>11.9 _mysql_connector.MySQL.commit() Method</h2></div></div></div><a class="indexterm" name="id5611"></a><a class="indexterm" name="id5613"></a><p>
6226 Syntax:
6227 </p><pre data-lang="python" class="programlisting">ccnx.commit()
6228 </pre><p>
6229 Commits the current transaction.
6230 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-connect"></a>11.10 _mysql_connector.MySQL.connect() Method</h2></div></div></div><a class="indexterm" name="id5620"></a><a class="indexterm" name="id5622"></a><p>
6231 Syntax:
6232 </p><pre data-lang="python" class="programlisting">ccnx.connect(<em class="replaceable"><code>args</code></em>)
6233 </pre><p>
6234 Connects to a MySQL server.
6235 </p><pre data-lang="python" class="programlisting">import _mysql_connector
6236
6237 ccnx = _mysql_connector.MySQL()
6238 ccnx.connect(user='scott', password='<em class="replaceable"><code>password</code></em>',
6239 host='127.0.0.1', database='employees')
6240 ccnx.close()
6241 </pre><p>
6242 <code class="literal">connect()</code> supports the following arguments:
6243 <code class="literal">host</code>, <code class="literal">user</code>,
6244 <code class="literal">password</code>, <code class="literal">database</code>,
6245 <code class="literal">port</code>, <code class="literal">unix_socket</code>,
6246 <code class="literal">client_flags</code>, <code class="literal">ssl_ca</code>,
6247 <code class="literal">ssl_cert</code>, <code class="literal">ssl_key</code>,
6248 <code class="literal">ssl_verify_cert</code>, <code class="literal">compress</code>.
6249 See <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
6250 </p><p>
6251 If <code class="literal">ccnx</code> is already connected,
6252 <code class="literal">connect()</code> discards any pending result set and
6253 closes the connection before reopening it.
6254 </p><p>
6255 Raises a <code class="literal">TypeError</code> exception if any argument is
6256 of an invalid type.
6257 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-connected"></a>11.11 _mysql_connector.MySQL.connected() Method</h2></div></div></div><a class="indexterm" name="id5652"></a><a class="indexterm" name="id5654"></a><p>
6258 Syntax:
6259 </p><pre data-lang="python" class="programlisting">is_connected = ccnx.connected()
6260 </pre><p>
6261 Returns <code class="literal">True</code> or <code class="literal">False</code> to
6262 indicate whether the <code class="literal">MySQL</code> instance is
6263 connected.
6264 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-consume-result"></a>11.12 _mysql_connector.MySQL.consume_result() Method</h2></div></div></div><a class="indexterm" name="id5664"></a><a class="indexterm" name="id5666"></a><p>
6265 Syntax:
6266 </p><pre data-lang="python" class="programlisting">ccnx.consume_result()
6267 </pre><p>
6268 Consumes the stored result set, if there is one, for this
6269 <code class="literal">MySQL</code> instance, by fetching all rows. If the
6270 statement that was executed returned multiple result sets, this
6271 method loops over and consumes all of them.
6272 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-convert-to-mysql"></a>11.13 _mysql_connector.MySQL.convert_to_mysql() Method</h2></div></div></div><a class="indexterm" name="id5674"></a><a class="indexterm" name="id5676"></a><p>
6273 Syntax:
6274 </p><pre data-lang="python" class="programlisting">converted_obj = ccnx.convert_to_mysql(<em class="replaceable"><code>obj</code></em>))
6275 </pre><p>
6276 Converts a Python object to a MySQL value based on the Python type
6277 of the object. The converted object is escaped and quoted.
6278 </p><pre data-lang="python" class="programlisting">ccnx.query('SELECT CURRENT_USER(), 1 + 3, NOW()')
6279 row = ccnx.fetch_row()
6280 for col in row:
6281 print(ccnx.convert_to_mysql(col))
6282 ccnx.consume_result()
6283 </pre><p>
6284 Raises a <code class="literal">MySQLInterfaceError</code> exception if the
6285 Python object cannot be converted.
6286 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-escape-string"></a>11.14 _mysql_connector.MySQL.escape_string() Method</h2></div></div></div><a class="indexterm" name="id5687"></a><a class="indexterm" name="id5689"></a><p>
6287 Syntax:
6288 </p><pre data-lang="python" class="programlisting">str = ccnx.escape_string(<em class="replaceable"><code>str_to_escape</code></em>)
6289 </pre><p>
6290 Uses the <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-escape-string.html" target="_top"><code class="literal">mysql_escape_string()</code></a> C
6291 API function to create an SQL string that you can use in an SQL
6292 statement.
6293 </p><p>
6294 Raises a <code class="literal">TypeError</code> exception if the value does
6295 not have a <code class="literal">Unicode</code>, <code class="literal">bytes</code>,
6296 or (for Python 2) <code class="literal">string</code> type. Raises a
6297 <code class="literal">MySQLError</code> exception if the string could not be
6298 escaped.
6299 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-fetch-fields"></a>11.15 _mysql_connector.MySQL.fetch_fields() Method</h2></div></div></div><a class="indexterm" name="id5705"></a><a class="indexterm" name="id5707"></a><p>
6300 Syntax:
6301 </p><pre data-lang="python" class="programlisting">field_info = ccnx.fetch_fields()
6302 </pre><p>
6303 Fetches column information for the active result set. Returns a
6304 list of tuples, one tuple per column
6305 </p><p>
6306 Raises a <code class="literal">MySQLInterfaceError</code> exception for any
6307 MySQL error returned by the MySQL server.
6308 </p><pre data-lang="python" class="programlisting">ccnx.query('SELECT CURRENT_USER(), 1 + 3, NOW()')
6309 field_info = ccnx.fetch_fields()
6310 for fi in field_info:
6311 print(fi)
6312 ccnx.consume_result()
6313 </pre></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-fetch-row"></a>11.16 _mysql_connector.MySQL.fetch_row() Method</h2></div></div></div><a class="indexterm" name="id5717"></a><a class="indexterm" name="id5719"></a><p>
6314 Syntax:
6315 </p><pre data-lang="python" class="programlisting">row = ccnx.fetch_row()
6316 </pre><p>
6317 Fetches the next row from the active result set. The row is
6318 returned as a tuple that contains the values converted to Python
6319 objects, unless <code class="literal">raw</code> was set.
6320 </p><pre data-lang="python" class="programlisting">ccnx.query('SELECT CURRENT_USER(), 1 + 3, NOW()')
6321 row = ccnx.fetch_row()
6322 print(row)
6323 ccnx.free_result()
6324 </pre><p>
6325 Raises a <code class="literal">MySQLInterfaceError</code> exception for any
6326 MySQL error returned by the MySQL server.
6327 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-field-count"></a>11.17 _mysql_connector.MySQL.field_count() Method</h2></div></div></div><a class="indexterm" name="id5730"></a><a class="indexterm" name="id5732"></a><p>
6328 Syntax:
6329 </p><pre data-lang="python" class="programlisting">count = ccnx.field_count()
6330 </pre><p>
6331 Returns the number of columns in the active result set.
6332 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-free-result"></a>11.18 _mysql_connector.MySQL.free_result() Method</h2></div></div></div><a class="indexterm" name="id5739"></a><a class="indexterm" name="id5741"></a><p>
6333 Syntax:
6334 </p><pre data-lang="python" class="programlisting">ccnx.free_result()
6335 </pre><p>
6336 Frees the stored result set, if there is one, for this
6337 <code class="literal">MySQL</code> instance. If the statement that was
6338 executed returned multiple result sets, this method loops over and
6339 consumes all of them.
6340 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-character-set-info"></a>11.19 _mysql_connector.MySQL.get_character_set_info() Method</h2></div></div></div><a class="indexterm" name="id5749"></a><a class="indexterm" name="id5751"></a><p>
6341 Syntax:
6342 </p><pre data-lang="python" class="programlisting">info = ccnx.get_character_set_info()
6343 </pre><p>
6344 Returns information about the default character set for the
6345 current MySQL session. The returned dictionary has the keys
6346 <code class="literal">number</code>, <code class="literal">name</code>,
6347 <code class="literal">csname</code>, <code class="literal">comment</code>,
6348 <code class="literal">dir</code>, <code class="literal">mbminlen</code>, and
6349 <code class="literal">mbmaxlen</code>.
6350 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-client-info"></a>11.20 _mysql_connector.MySQL.get_client_info() Method</h2></div></div></div><a class="indexterm" name="id5765"></a><a class="indexterm" name="id5767"></a><p>
6351 Syntax:
6352 </p><pre data-lang="python" class="programlisting">info = ccnx.get_client_info()
6353 </pre><p>
6354 Returns the MySQL client library version as a string.
6355 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-client-version"></a>11.21 _mysql_connector.MySQL.get_client_version() Method</h2></div></div></div><a class="indexterm" name="id5774"></a><a class="indexterm" name="id5776"></a><p>
6356 Syntax:
6357 </p><pre data-lang="python" class="programlisting">info = ccnx.get_client_version()
6358 </pre><p>
6359 Returns the MySQL client library version as a tuple.
6360 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-host-info"></a>11.22 _mysql_connector.MySQL.get_host_info() Method</h2></div></div></div><a class="indexterm" name="id5783"></a><a class="indexterm" name="id5785"></a><p>
6361 Syntax:
6362 </p><pre data-lang="python" class="programlisting">info = ccnx.get_host_info()
6363 </pre><p>
6364 Returns a description of the type of connection in use as a
6365 string.
6366 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-proto-info"></a>11.23 _mysql_connector.MySQL.get_proto_info() Method</h2></div></div></div><a class="indexterm" name="id5792"></a><a class="indexterm" name="id5794"></a><p>
6367 Syntax:
6368 </p><pre data-lang="python" class="programlisting">info = ccnx.get_proto_info()
6369 </pre><p>
6370 Returns the protocol version used by the current session.
6371 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-server-info"></a>11.24 _mysql_connector.MySQL.get_server_info() Method</h2></div></div></div><a class="indexterm" name="id5801"></a><a class="indexterm" name="id5803"></a><p>
6372 Syntax:
6373 </p><pre data-lang="python" class="programlisting">info = ccnx.get_server_info()
6374 </pre><p>
6375 Returns the MySQL server version as a string.
6376 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-server-version"></a>11.25 _mysql_connector.MySQL.get_server_version() Method</h2></div></div></div><a class="indexterm" name="id5810"></a><a class="indexterm" name="id5812"></a><p>
6377 Syntax:
6378 </p><pre data-lang="python" class="programlisting">info = ccnx.get_server_version()
6379 </pre><p>
6380 Returns the MySQL server version as a tuple.
6381 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-ssl-cipher"></a>11.26 _mysql_connector.MySQL.get_ssl_cipher() Method</h2></div></div></div><a class="indexterm" name="id5819"></a><a class="indexterm" name="id5821"></a><p>
6382 Syntax:
6383 </p><pre data-lang="python" class="programlisting">info = ccnx.get_ssl_cipher()
6384 </pre><p>
6385 Returns the SSL cipher used for the current session, or
6386 <code class="literal">None</code> if SSL is not in use.
6387 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-hex-string"></a>11.27 _mysql_connector.MySQL.hex_string() Method</h2></div></div></div><a class="indexterm" name="id5829"></a><a class="indexterm" name="id5831"></a><p>
6388 Syntax:
6389 </p><pre data-lang="python" class="programlisting">str = ccnx.hex_string(<em class="replaceable"><code>string_to_hexify</code></em>)
6390 </pre><p>
6391 Encodes a value in hexadecimal format and wraps it within
6392 <code class="literal">X''</code>. For example, <code class="literal">"ham"</code>
6393 becomes <code class="literal">X'68616D'</code>.
6394 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-insert-id"></a>11.28 _mysql_connector.MySQL.insert_id() Method</h2></div></div></div><a class="indexterm" name="id5842"></a><a class="indexterm" name="id5844"></a><p>
6395 Syntax:
6396 </p><pre data-lang="python" class="programlisting">insert_id = ccnx.insert_id()
6397 </pre><p>
6398 Returns the <code class="literal">AUTO_INCREMENT</code> value generated by
6399 the most recent executed statement, or 0 if there is no such
6400 value.
6401 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-more-results"></a>11.29 _mysql_connector.MySQL.more_results() Method</h2></div></div></div><a class="indexterm" name="id5852"></a><a class="indexterm" name="id5854"></a><p>
6402 Syntax:
6403 </p><pre data-lang="python" class="programlisting">more = ccnx.more_results()
6404 </pre><p>
6405 Returns <code class="literal">True</code> or <code class="literal">False</code> to
6406 indicate whether any more result sets exist.
6407 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-next-result"></a>11.30 _mysql_connector.MySQL.next_result() Method</h2></div></div></div><a class="indexterm" name="id5863"></a><a class="indexterm" name="id5865"></a><p>
6408 Syntax:
6409 </p><pre data-lang="python" class="programlisting">ccnx.next_result()
6410 </pre><p>
6411 Initiates the next result set for a statement string that produced
6412 multiple result sets.
6413 </p><p>
6414 Raises a <code class="literal">MySQLInterfaceError</code> exception for any
6415 MySQL error returned by the MySQL server.
6416 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-num-fields"></a>11.31 _mysql_connector.MySQL.num_fields() Method</h2></div></div></div><a class="indexterm" name="id5874"></a><a class="indexterm" name="id5876"></a><p>
6417 Syntax:
6418 </p><pre data-lang="python" class="programlisting">count = ccnx.num_fields()
6419 </pre><p>
6420 Returns the number of columns in the active result set.
6421 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-num-rows"></a>11.32 _mysql_connector.MySQL.num_rows() Method</h2></div></div></div><a class="indexterm" name="id5883"></a><a class="indexterm" name="id5885"></a><p>
6422 Syntax:
6423 </p><pre data-lang="python" class="programlisting">count = ccnx.num_rows()
6424 </pre><p>
6425 Returns the number of rows in the active result set.
6426 </p><p>
6427 Raises a <code class="literal">MySQLError</code> exception if there is no
6428 result set.
6429 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-ping"></a>11.33 _mysql_connector.MySQL.ping() Method</h2></div></div></div><a class="indexterm" name="id5894"></a><a class="indexterm" name="id5896"></a><p>
6430 Syntax:
6431 </p><pre data-lang="python" class="programlisting">alive = ccnx.ping()
6432 </pre><p>
6433 Returns <code class="literal">True</code> or <code class="literal">False</code> to
6434 indicate whether the connection to the MySQL server is working.
6435 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-query"></a>11.34 _mysql_connector.MySQL.query() Method</h2></div></div></div><a class="indexterm" name="id5905"></a><a class="indexterm" name="id5907"></a><p>
6436 Syntax:
6437 </p><pre data-lang="python" class="programlisting">ccnx.query(<em class="replaceable"><code>args</code></em>)
6438 </pre><p>
6439 Executes an SQL statement. The permitted arguments are
6440 <code class="literal">statement</code>, <code class="literal">buffered</code>,
6441 <code class="literal">raw</code>, and <code class="literal">raw_as_string</code>.
6442 </p><pre data-lang="python" class="programlisting">ccnx.query('DROP TABLE IF EXISTS t')
6443 ccnx.query('CREATE TABLE t (i INT NOT NULL AUTO_INCREMENT PRIMARY KEY)')
6444 ccnx.query('INSERT INTO t (i) VALUES (NULL),(NULL),(NULL)')
6445 ccnx.query('SELECT LAST_INSERT_ID()')
6446 row = ccnx.fetch_row()
6447 print('LAST_INSERT_ID(): ', row)
6448 ccnx.consume_result()
6449 </pre><p>
6450 <code class="literal">buffered</code> and <code class="literal">raw</code>, if not
6451 provided, take their values from the <code class="literal">MySQL</code>
6452 instance. <code class="literal">raw_as_string</code> is a special argument
6453 for Python v2 and returns <code class="literal">str</code> instead of
6454 <code class="literal">bytearray</code> (compatible with Connector/Python
6455 v1.x).
6456 </p><p>
6457 To check whether the query returns rows, check the
6458 <code class="literal">have_result_set</code> property of the
6459 <code class="literal">MySQL</code> instance.
6460 </p><p>
6461 <code class="literal">query()</code> returns <code class="literal">True</code> if the
6462 query executes, and raises an exception otherwise. It raises a
6463 <code class="literal">TypeError</code> exception if any argument has an
6464 invalid type, and a <code class="literal">MySQLInterfaceError</code>
6465 exception for any MySQL error returned by the MySQL server.
6466 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-raw"></a>11.35 _mysql_connector.MySQL.raw() Method</h2></div></div></div><a class="indexterm" name="id5935"></a><a class="indexterm" name="id5937"></a><p>
6467 Syntax:
6468 </p><pre data-lang="python" class="programlisting">is_raw = ccnx.raw() # getter
6469 ccnx.raw(<em class="replaceable"><code>bool</code></em>) # setter
6470 </pre><p>
6471 With no argument, returns <code class="literal">True</code> or
6472 <code class="literal">False</code> to indicate whether the
6473 <code class="literal">MySQL</code> instance return the rows as is (without
6474 conversion to Python objects).
6475 </p><p>
6476 With a boolean argument, sets the <code class="literal">MySQL</code>
6477 instance raw mode.
6478 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-refresh"></a>11.36 _mysql_connector.MySQL.refresh() Method</h2></div></div></div><a class="indexterm" name="id5950"></a><a class="indexterm" name="id5952"></a><p>
6479 Syntax:
6480 </p><pre data-lang="python" class="programlisting">ccnx.refresh(<em class="replaceable"><code>flags</code></em>)
6481 </pre><p>
6482 Flushes or resets the tables and caches indicated by the argument.
6483 The only argument currently permitted is an integer.
6484 </p><p>
6485 Raises a <code class="literal">TypeError</code> exception if the first
6486 argument is not an integer.
6487 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-reset-connection"></a>11.37 _mysql_connector.MySQL.reset_connection() Method</h2></div></div></div><a class="indexterm" name="id5962"></a><a class="indexterm" name="id5964"></a><p>
6488 Syntax:
6489 </p><pre data-lang="python" class="programlisting">ccnx.reset_connection()
6490 </pre><p>
6491 Resets the user variables and session variables for a connection
6492 session.
6493 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-rollback"></a>11.38 _mysql_connector.MySQL.rollback() Method</h2></div></div></div><a class="indexterm" name="id5971"></a><a class="indexterm" name="id5973"></a><p>
6494 Syntax:
6495 </p><pre data-lang="python" class="programlisting">ccnx.rollback()
6496 </pre><p>
6497 Rolls back the current transaction.
6498 </p><p>
6499 Raises a <code class="literal">MySQLInterfaceError</code> exception on
6500 errors.
6501 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-select-db"></a>11.39 _mysql_connector.MySQL.select_db() Method</h2></div></div></div><a class="indexterm" name="id5982"></a><a class="indexterm" name="id5984"></a><p>
6502 Syntax:
6503 </p><pre data-lang="python" class="programlisting">ccnx.select_db(<em class="replaceable"><code>db_name</code></em>)
6504 </pre><p>
6505 Sets the default (current) database for the current session.
6506 </p><p>
6507 Raises a <code class="literal">MySQLInterfaceError</code> exception for any
6508 MySQL error returned by the MySQL server.
6509 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-set-character-set"></a>11.40 _mysql_connector.MySQL.set_character_set() Method</h2></div></div></div><a class="indexterm" name="id5994"></a><a class="indexterm" name="id5996"></a><p>
6510 Syntax:
6511 </p><pre data-lang="python" class="programlisting">ccnx.set_character_set(<em class="replaceable"><code>charset_name</code></em>)
6512 </pre><p>
6513 Sets the default character set for the current session. The only
6514 argument permitted is a string that contains the character set
6515 name.
6516 </p><p>
6517 Raises a <code class="literal">TypeError</code> exception if the argument is
6518 not a <code class="literal">PyString_type</code>.
6519 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-shutdown"></a>11.41 _mysql_connector.MySQL.shutdown() Method</h2></div></div></div><a class="indexterm" name="id6007"></a><a class="indexterm" name="id6009"></a><p>
6520 Syntax:
6521 </p><pre data-lang="python" class="programlisting">ccnx.shutdown(<em class="replaceable"><code>flags</code></em>)
6522 </pre><p>
6523 Shuts down the MySQL server. The only argument currently permitted
6524 is an integer that describes the shutdown type.
6525 </p><p>
6526 Raises a <code class="literal">TypeError</code> exception if the first
6527 argument is not an integer. Raises a
6528 <code class="literal">MySQLErrorInterface</code> exception if an error is
6529 retured by the MySQL server.
6530 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-stat"></a>11.42 _mysql_connector.MySQL.stat() Method</h2></div></div></div><a class="indexterm" name="id6020"></a><a class="indexterm" name="id6022"></a><p>
6531 Syntax:
6532 </p><pre data-lang="python" class="programlisting">info = ccnx.stat()
6533 </pre><p>
6534 Returns the server status as a string.
6535 </p><p>
6536 Raises a <code class="literal">MySQLErrorInterface</code> exception if an
6537 error is retured by the MySQL server.
6538 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-thread-id"></a>11.43 _mysql_connector.MySQL.thread_id() Method</h2></div></div></div><a class="indexterm" name="id6031"></a><a class="indexterm" name="id6033"></a><p>
6539 Syntax:
6540 </p><pre data-lang="python" class="programlisting">thread_id = ccnx.thread_id()
6541 </pre><p>
6542 Returns the current thread or connection ID.
6543 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-use-unicode"></a>11.44 _mysql_connector.MySQL.use_unicode() Method</h2></div></div></div><a class="indexterm" name="id6040"></a><a class="indexterm" name="id6042"></a><p>
6544 Syntax:
6545 </p><pre data-lang="python" class="programlisting">is_unicode = ccnx.use_unicode() # getter
6546 ccnx.use_unicode(<em class="replaceable"><code>bool</code></em>) # setter
6547 </pre><p>
6548 With no argument, returns <code class="literal">True</code> or
6549 <code class="literal">False</code> to indicate whether the
6550 <code class="literal">MySQL</code> instance returns nonbinary strings as
6551 Unicode.
6552 </p><p>
6553 With a boolean argument, sets whether the <code class="literal">MySQL</code>
6554 instance returns nonbinary strings as Unicode.
6555 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-warning-count"></a>11.45 _mysql_connector.MySQL.warning_count() Method</h2></div></div></div><a class="indexterm" name="id6055"></a><a class="indexterm" name="id6057"></a><p>
6556 Syntax:
6557 </p><pre data-lang="python" class="programlisting">count = ccnx.warning_count()
6558 </pre><p>
6559 Returns the number of errors, warnings, and notes produced by the
6560 previous SQL statement.
6561 </p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-have-result-set"></a>11.46 _mysql_connector.MySQL.have_result_set Property</h2></div></div></div><a class="indexterm" name="id6064"></a><a class="indexterm" name="id6066"></a><p>
6562 Syntax:
6563 </p><pre data-lang="python" class="programlisting">has_rows = ccnx.have_result_set
6564 </pre><p>
6565 After execution of the <code class="literal">query()</code> method, this
6566 property indicates whether the query returns rows.
6567 </p></div></div><div class="index"><div class="titlepage"><div><div><h1 class="title"><a name="ix01"></a>Index</h1></div></div></div><div xmlns:xlink="http://www.w3.org/1999/xlink" class="index"><p><a href="#connector-python_index0_Symbols">Symbols</a>
6568 &nbsp;|&nbsp;<a href="#connector-python_index0_C">C</a>
6569 &nbsp;|&nbsp;<a href="#connector-python_index0_D">D</a>
6570 &nbsp;|&nbsp;<a href="#connector-python_index0_E">E</a>
6571 &nbsp;|&nbsp;<a href="#connector-python_index0_F">F</a>
6572 &nbsp;|&nbsp;<a href="#connector-python_index0_M">M</a>
6573 &nbsp;|&nbsp;<a href="#connector-python_index0_P">P</a>
6574 &nbsp;|&nbsp;<a href="#connector-python_index0_S">S</a>
6575 </p><div class="indexdiv"><h3><a name="connector-python_index0_Symbols"></a>Symbols</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id5489">_mysql_connector module, <a class="indexterm" href="#connector-python-api-cext-mysql-connector">_mysql_connector Module</a></dt><dt id="ientry-id5497">_mysql_connector.MySQL() class, <a class="indexterm" href="#connector-python-api-cext-mysql">_mysql_connector.MySQL() Class</a></dt><dt id="ientry-id5526">_mysql_connector.MySQL.affected_rows() method, <a class="indexterm" href="#connector-python-api-cext-affected-rows">_mysql_connector.MySQL.affected_rows() Method</a></dt><dt id="ientry-id5541">_mysql_connector.MySQL.autocommit() method, <a class="indexterm" href="#connector-python-api-cext-autocommit">_mysql_connector.MySQL.autocommit() Method</a></dt><dt id="ientry-id5556">_mysql_connector.MySQL.buffered() method, <a class="indexterm" href="#connector-python-api-cext-buffered">_mysql_connector.MySQL.buffered() Method</a></dt><dt id="ientry-id5575">_mysql_connector.MySQL.change_user() method, <a class="indexterm" href="#connector-python-api-cext-change-user">_mysql_connector.MySQL.change_user() Method</a></dt><dt id="ientry-id5590">_mysql_connector.MySQL.character_set_name() method, <a class="indexterm" href="#connector-python-api-cext-character-set-name">_mysql_connector.MySQL.character_set_name() Method</a></dt><dt id="ientry-id5602">_mysql_connector.MySQL.close() method, <a class="indexterm" href="#connector-python-api-cext-close">_mysql_connector.MySQL.close() Method</a></dt><dt id="ientry-id5611">_mysql_connector.MySQL.commit() method, <a class="indexterm" href="#connector-python-api-cext-commit">_mysql_connector.MySQL.commit() Method</a></dt><dt id="ientry-id5620">_mysql_connector.MySQL.connect() method, <a class="indexterm" href="#connector-python-api-cext-connect">_mysql_connector.MySQL.connect() Method</a></dt><dt id="ientry-id5652">_mysql_connector.MySQL.connected() method, <a class="indexterm" href="#connector-python-api-cext-connected">_mysql_connector.MySQL.connected() Method</a></dt><dt id="ientry-id5664">_mysql_connector.MySQL.consume_result() method, <a class="indexterm" href="#connector-python-api-cext-consume-result">_mysql_connector.MySQL.consume_result() Method</a></dt><dt id="ientry-id5674">_mysql_connector.MySQL.convert_to_mysql() method, <a class="indexterm" href="#connector-python-api-cext-convert-to-mysql">_mysql_connector.MySQL.convert_to_mysql() Method</a></dt><dt id="ientry-id5687">_mysql_connector.MySQL.escape_string() method, <a class="indexterm" href="#connector-python-api-cext-escape-string">_mysql_connector.MySQL.escape_string() Method</a></dt><dt id="ientry-id5705">_mysql_connector.MySQL.fetch_fields() method, <a class="indexterm" href="#connector-python-api-cext-fetch-fields">_mysql_connector.MySQL.fetch_fields() Method</a></dt><dt id="ientry-id5717">_mysql_connector.MySQL.fetch_row() method, <a class="indexterm" href="#connector-python-api-cext-fetch-row">_mysql_connector.MySQL.fetch_row() Method</a></dt><dt id="ientry-id5730">_mysql_connector.MySQL.field_count() method, <a class="indexterm" href="#connector-python-api-cext-field-count">_mysql_connector.MySQL.field_count() Method</a></dt><dt id="ientry-id5739">_mysql_connector.MySQL.free_result() method, <a class="indexterm" href="#connector-python-api-cext-free-result">_mysql_connector.MySQL.free_result() Method</a></dt><dt id="ientry-id5749">_mysql_connector.MySQL.get_character_set_info() method, <a class="indexterm" href="#connector-python-api-cext-get-character-set-info">_mysql_connector.MySQL.get_character_set_info() Method</a></dt><dt id="ientry-id5765">_mysql_connector.MySQL.get_client_info() method, <a class="indexterm" href="#connector-python-api-cext-get-client-info">_mysql_connector.MySQL.get_client_info() Method</a></dt><dt id="ientry-id5774">_mysql_connector.MySQL.get_client_version() method, <a class="indexterm" href="#connector-python-api-cext-get-client-version">_mysql_connector.MySQL.get_client_version() Method</a></dt><dt id="ientry-id5783">_mysql_connector.MySQL.get_host_info() method, <a class="indexterm" href="#connector-python-api-cext-get-host-info">_mysql_connector.MySQL.get_host_info() Method</a></dt><dt id="ientry-id5792">_mysql_connector.MySQL.get_proto_info() method, <a class="indexterm" href="#connector-python-api-cext-get-proto-info">_mysql_connector.MySQL.get_proto_info() Method</a></dt><dt id="ientry-id5801">_mysql_connector.MySQL.get_server_info() method, <a class="indexterm" href="#connector-python-api-cext-get-server-info">_mysql_connector.MySQL.get_server_info() Method</a></dt><dt id="ientry-id5810">_mysql_connector.MySQL.get_server_version() method, <a class="indexterm" href="#connector-python-api-cext-get-server-version">_mysql_connector.MySQL.get_server_version() Method</a></dt><dt id="ientry-id5819">_mysql_connector.MySQL.get_ssl_cipher() method, <a class="indexterm" href="#connector-python-api-cext-get-ssl-cipher">_mysql_connector.MySQL.get_ssl_cipher() Method</a></dt><dt id="ientry-id6064">_mysql_connector.MySQL.have_result_set property, <a class="indexterm" href="#connector-python-api-cext-have-result-set">_mysql_connector.MySQL.have_result_set Property</a></dt><dt id="ientry-id5829">_mysql_connector.MySQL.hex_string() method, <a class="indexterm" href="#connector-python-api-cext-hex-string">_mysql_connector.MySQL.hex_string() Method</a></dt><dt id="ientry-id5842">_mysql_connector.MySQL.insert_id() method, <a class="indexterm" href="#connector-python-api-cext-insert-id">_mysql_connector.MySQL.insert_id() Method</a></dt><dt id="ientry-id5852">_mysql_connector.MySQL.more_results() method, <a class="indexterm" href="#connector-python-api-cext-more-results">_mysql_connector.MySQL.more_results() Method</a></dt><dt id="ientry-id5863">_mysql_connector.MySQL.next_result() method, <a class="indexterm" href="#connector-python-api-cext-next-result">_mysql_connector.MySQL.next_result() Method</a></dt><dt id="ientry-id5874">_mysql_connector.MySQL.num_fields() method, <a class="indexterm" href="#connector-python-api-cext-num-fields">_mysql_connector.MySQL.num_fields() Method</a></dt><dt id="ientry-id5883">_mysql_connector.MySQL.num_rows() method, <a class="indexterm" href="#connector-python-api-cext-num-rows">_mysql_connector.MySQL.num_rows() Method</a></dt><dt id="ientry-id5894">_mysql_connector.MySQL.ping() method, <a class="indexterm" href="#connector-python-api-cext-ping">_mysql_connector.MySQL.ping() Method</a></dt><dt id="ientry-id5905">_mysql_connector.MySQL.query() method, <a class="indexterm" href="#connector-python-api-cext-query">_mysql_connector.MySQL.query() Method</a></dt><dt id="ientry-id5935">_mysql_connector.MySQL.raw() method, <a class="indexterm" href="#connector-python-api-cext-raw">_mysql_connector.MySQL.raw() Method</a></dt><dt id="ientry-id5950">_mysql_connector.MySQL.refresh() method, <a class="indexterm" href="#connector-python-api-cext-refresh">_mysql_connector.MySQL.refresh() Method</a></dt><dt id="ientry-id5962">_mysql_connector.MySQL.reset_connection() method, <a class="indexterm" href="#connector-python-api-cext-reset-connection">_mysql_connector.MySQL.reset_connection() Method</a></dt><dt id="ientry-id5971">_mysql_connector.MySQL.rollback() method, <a class="indexterm" href="#connector-python-api-cext-rollback">_mysql_connector.MySQL.rollback() Method</a></dt><dt id="ientry-id5982">_mysql_connector.MySQL.select_db() method, <a class="indexterm" href="#connector-python-api-cext-select-db">_mysql_connector.MySQL.select_db() Method</a></dt><dt id="ientry-id5994">_mysql_connector.MySQL.set_character_set() method, <a class="indexterm" href="#connector-python-api-cext-set-character-set">_mysql_connector.MySQL.set_character_set() Method</a></dt><dt id="ientry-id6007">_mysql_connector.MySQL.shutdown() method, <a class="indexterm" href="#connector-python-api-cext-shutdown">_mysql_connector.MySQL.shutdown() Method</a></dt><dt id="ientry-id6020">_mysql_connector.MySQL.stat() method, <a class="indexterm" href="#connector-python-api-cext-stat">_mysql_connector.MySQL.stat() Method</a></dt><dt id="ientry-id6031">_mysql_connector.MySQL.thread_id() method, <a class="indexterm" href="#connector-python-api-cext-thread-id">_mysql_connector.MySQL.thread_id() Method</a></dt><dt id="ientry-id6040">_mysql_connector.MySQL.use_unicode() method, <a class="indexterm" href="#connector-python-api-cext-use-unicode">_mysql_connector.MySQL.use_unicode() Method</a></dt><dt id="ientry-id6055">_mysql_connector.MySQL.warning_count() method, <a class="indexterm" href="#connector-python-api-cext-warning-count">_mysql_connector.MySQL.warning_count() Method</a></dt></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_C"></a>C</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id3380">class</dt><dd><dl><dt>connection.MySQLConnection, <a class="indexterm" href="#connector-python-api-mysqlconnection">connection.MySQLConnection Class</a></dt><dt>constants.CharacterSet, <a class="indexterm" href="#connector-python-api-characterset">constants.CharacterSet Class</a></dt><dt>constants.ClientFlag, <a class="indexterm" href="#connector-python-api-clientflag">constants.ClientFlag Class</a></dt><dt>constants.FieldType, <a class="indexterm" href="#connector-python-api-fieldtype">constants.FieldType Class</a></dt><dt>constants.RefreshOption, <a class="indexterm" href="#connector-python-api-refreshoption">constants.RefreshOption Class</a></dt><dt>constants.SQLMode, <a class="indexterm" href="#connector-python-api-sqlmode">constants.SQLMode Class</a></dt><dt>cursor.MySQLCursor, <a class="indexterm" href="#connector-python-api-mysqlcursor">cursor.MySQLCursor Class</a></dt><dt>cursor.MySQLCursorBuffered, <a class="indexterm" href="#connector-python-api-mysqlcursorbuffered">cursor.MySQLCursorBuffered Class</a></dt><dt>cursor.MySQLCursorBufferedDict, <a class="indexterm" href="#connector-python-api-mysqlcursorbuffereddict">cursor.MySQLCursorBufferedDict Class</a></dt><dt>cursor.MySQLCursorDict, <a class="indexterm" href="#connector-python-api-mysqlcursordict">cursor.MySQLCursorDict Class</a></dt><dt>cursor.MySQLCursorPrepared, <a class="indexterm" href="#connector-python-api-mysqlcursorprepared">cursor.MySQLCursorPrepared Class</a></dt><dt>cursor.MySQLCursorRaw, <a class="indexterm" href="#connector-python-api-mysqlcursorraw">cursor.MySQLCursorRaw Class</a></dt><dt>pooling.MySQLConnectionPool, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool">pooling.MySQLConnectionPool Class</a></dt><dt>pooling.PooledMySQLConnection, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection">pooling.PooledMySQLConnection Class</a></dt><dt>_mysql_connector.MySQL(), <a class="indexterm" href="#connector-python-api-cext-mysql">_mysql_connector.MySQL() Class</a></dt></dl></dd><dt id="ientry-id5012">COM_STMT_SEND_LONG_DATA</dt><dd><dl><dt>prepared statements, <a class="indexterm" href="#connector-python-api-mysqlcursorprepared">cursor.MySQLCursorPrepared Class</a></dt></dl></dd><dt id="ientry-id3378">connection.MySQLConnection class, <a class="indexterm" href="#connector-python-api-mysqlconnection">connection.MySQLConnection Class</a></dt><dt id="ientry-id3386">connection.MySQLConnection() constructor, <a class="indexterm" href="#connector-python-api-mysqlconnection-constructor">connection.MySQLConnection() Constructor</a></dt><dt id="ientry-id1571">Connector/Python, <a class="indexterm" href="#connector-python-introduction">Introduction to MySQL Connector/Python</a></dt><dt id="ientry-id5059">constants.CharacterSet class, <a class="indexterm" href="#connector-python-api-characterset">constants.CharacterSet Class</a></dt><dt id="ientry-id5020">constants.ClientFlag class, <a class="indexterm" href="#connector-python-api-clientflag">constants.ClientFlag Class</a></dt><dt id="ientry-id5036">constants.FieldType class, <a class="indexterm" href="#connector-python-api-fieldtype">constants.FieldType Class</a></dt><dt id="ientry-id5069">constants.RefreshOption class, <a class="indexterm" href="#connector-python-api-refreshoption">constants.RefreshOption Class</a></dt><dt id="ientry-id5047">constants.SQLMode class, <a class="indexterm" href="#connector-python-api-sqlmode">constants.SQLMode Class</a></dt><dt id="ientry-id3388">constructor</dt><dd><dl><dt>connection.MySQLConnection(), <a class="indexterm" href="#connector-python-api-mysqlconnection-constructor">connection.MySQLConnection() Constructor</a></dt><dt>cursor.MySQLCursor, <a class="indexterm" href="#connector-python-api-mysqlcursor-constructor">cursor.MySQLCursor Constructor</a></dt><dt>pooling.MySQLConnectionPool, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-constructor">pooling.MySQLConnectionPool Constructor</a></dt><dt>pooling.PooledMySQLConnection, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-constructor">pooling.PooledMySQLConnection Constructor</a></dt></dl></dd><dt id="ientry-id4844">cursor.mysqlcursor</dt><dd><dl><dt>Subclasses, <a class="indexterm" href="#connector-python-api-cursor-subclasses">Subclasses cursor.MySQLCursor</a></dt></dl></dd><dt id="ientry-id4399">cursor.MySQLCursor class, <a class="indexterm" href="#connector-python-api-mysqlcursor">cursor.MySQLCursor Class</a></dt><dt id="ientry-id4441">cursor.MySQLCursor constructor, <a class="indexterm" href="#connector-python-api-mysqlcursor-constructor">cursor.MySQLCursor Constructor</a></dt><dt id="ientry-id4851">cursor.MySQLCursorBuffered class, <a class="indexterm" href="#connector-python-api-mysqlcursorbuffered">cursor.MySQLCursorBuffered Class</a></dt><dt id="ientry-id4918">cursor.MySQLCursorBufferedDict class, <a class="indexterm" href="#connector-python-api-mysqlcursorbuffereddict">cursor.MySQLCursorBufferedDict Class</a></dt><dt id="ientry-id4899">cursor.MySQLCursorDict class, <a class="indexterm" href="#connector-python-api-mysqlcursordict">cursor.MySQLCursorDict Class</a></dt><dt id="ientry-id4936">cursor.MySQLCursorPrepared class, <a class="indexterm" href="#connector-python-api-mysqlcursorprepared">cursor.MySQLCursorPrepared Class</a></dt><dt id="ientry-id4879">cursor.MySQLCursorRaw class, <a class="indexterm" href="#connector-python-api-mysqlcursorraw">cursor.MySQLCursorRaw Class</a></dt></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_D"></a>D</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id2948">DYLD_LIBRARY_PATH environment variable, <a class="indexterm" href="#connector-python-cext-development">Application Development with the Connector/Python C Extension</a></dt></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_E"></a>E</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id2950">environment variable</dt><dd><dl><dt>DYLD_LIBRARY_PATH, <a class="indexterm" href="#connector-python-cext-development">Application Development with the Connector/Python C Extension</a></dt></dl></dd><dt id="ientry-id5295">errorcode module, <a class="indexterm" href="#connector-python-api-errorcode">errorcode Module</a></dt><dt id="ientry-id5453">errors.custom_error_exception() function, <a class="indexterm" href="#connector-python-api-errors-custom-error-exception">errors.custom_error_exception() Function</a></dt><dt id="ientry-id5357">errors.DatabaseError exception, <a class="indexterm" href="#connector-python-api-errors-databaseerror">errors.DatabaseError Exception</a></dt><dt id="ientry-id5345">errors.DataError exception, <a class="indexterm" href="#connector-python-api-errors-dataerror">errors.DataError Exception</a></dt><dt id="ientry-id5305">errors.Error exception, <a class="indexterm" href="#connector-python-api-errors-error">errors.Error Exception</a></dt><dt id="ientry-id5367">errors.IntegrityError exception, <a class="indexterm" href="#connector-python-api-errors-integrityerror">errors.IntegrityError Exception</a></dt><dt id="ientry-id5379">errors.InterfaceError exception, <a class="indexterm" href="#connector-python-api-errors-interfaceerror">errors.InterfaceError Exception</a></dt><dt id="ientry-id5389">errors.InternalError exception, <a class="indexterm" href="#connector-python-api-errors-internalerror">errors.InternalError Exception</a></dt><dt id="ientry-id5399">errors.NotSupportedError exception, <a class="indexterm" href="#connector-python-api-errors-notsupportederror">errors.NotSupportedError Exception</a></dt><dt id="ientry-id5409">errors.OperationalError exception, <a class="indexterm" href="#connector-python-api-errors-operationalerror">errors.OperationalError Exception</a></dt><dt id="ientry-id5419">errors.PoolError exception, <a class="indexterm" href="#connector-python-api-errors-poolerror">errors.PoolError Exception</a></dt><dt id="ientry-id5428">errors.ProgrammingError exception, <a class="indexterm" href="#connector-python-api-errors-programmingerror">errors.ProgrammingError Exception</a></dt><dt id="ientry-id5440">errors.Warning exception, <a class="indexterm" href="#connector-python-api-errors-warning">errors.Warning Exception</a></dt><dt id="ientry-id5307">exception</dt><dd><dl><dt>errors.DatabaseError, <a class="indexterm" href="#connector-python-api-errors-databaseerror">errors.DatabaseError Exception</a></dt><dt>errors.DataError, <a class="indexterm" href="#connector-python-api-errors-dataerror">errors.DataError Exception</a></dt><dt>errors.Error, <a class="indexterm" href="#connector-python-api-errors-error">errors.Error Exception</a></dt><dt>errors.IntegrityError, <a class="indexterm" href="#connector-python-api-errors-integrityerror">errors.IntegrityError Exception</a></dt><dt>errors.InterfaceError, <a class="indexterm" href="#connector-python-api-errors-interfaceerror">errors.InterfaceError Exception</a></dt><dt>errors.InternalError, <a class="indexterm" href="#connector-python-api-errors-internalerror">errors.InternalError Exception</a></dt><dt>errors.NotSupportedError, <a class="indexterm" href="#connector-python-api-errors-notsupportederror">errors.NotSupportedError Exception</a></dt><dt>errors.OperationalError, <a class="indexterm" href="#connector-python-api-errors-operationalerror">errors.OperationalError Exception</a></dt><dt>errors.PoolError, <a class="indexterm" href="#connector-python-api-errors-poolerror">errors.PoolError Exception</a></dt><dt>errors.ProgrammingError, <a class="indexterm" href="#connector-python-api-errors-programmingerror">errors.ProgrammingError Exception</a></dt><dt>errors.Warning, <a class="indexterm" href="#connector-python-api-errors-warning">errors.Warning Exception</a></dt></dl></dd></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_F"></a>F</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id5455">function</dt><dd><dl><dt>errors.custom_error_exception(), <a class="indexterm" href="#connector-python-api-errors-custom-error-exception">errors.custom_error_exception() Function</a></dt></dl></dd></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_M"></a>M</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id3326">method</dt><dd><dl><dt>mysql.connector.connect(), <a class="indexterm" href="#connector-python-api-mysql-connector-connect">mysql.connector.connect() Method</a></dt><dt>MySQLConnection.close(), <a class="indexterm" href="#connector-python-api-mysqlconnection-close">MySQLConnection.close() Method</a></dt><dt>MySQLConnection.cmd_change_user(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-change-user">MySQLConnection.cmd_change_user() Method</a></dt><dt>MySQLConnection.cmd_debug(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-debug">MySQLConnection.cmd_debug() Method</a></dt><dt>MySQLConnection.cmd_init_db(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-init-db">MySQLConnection.cmd_init_db() Method</a></dt><dt>MySQLConnection.cmd_ping(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-ping">MySQLConnection.cmd_ping() Method</a></dt><dt>MySQLConnection.cmd_process_info(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-process-info">MySQLConnection.cmd_process_info() Method</a></dt><dt>MySQLConnection.cmd_process_kill(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-process-kill">MySQLConnection.cmd_process_kill() Method</a></dt><dt>MySQLConnection.cmd_query(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-query">MySQLConnection.cmd_query() Method</a></dt><dt>MySQLConnection.cmd_query_iter(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-query-iter">MySQLConnection.cmd_query_iter() Method</a></dt><dt>MySQLConnection.cmd_quit(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-quit">MySQLConnection.cmd_quit() Method</a></dt><dt>MySQLConnection.cmd_refresh(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-refresh">MySQLConnection.cmd_refresh() Method</a></dt><dt>MySQLConnection.cmd_reset_connection(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-reset-connection">MySQLConnection.cmd_reset_connection() Method</a></dt><dt>MySQLConnection.cmd_shutdown(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-shutdown">MySQLConnection.cmd_shutdown() Method</a></dt><dt>MySQLConnection.cmd_statistics(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-statistics">MySQLConnection.cmd_statistics() Method</a></dt><dt>MySQLConnection.commit(), <a class="indexterm" href="#connector-python-api-mysqlconnection-commit">MySQLConnection.commit() Method</a></dt><dt>MySQLConnection.config(), <a class="indexterm" href="#connector-python-api-mysqlconnection-config">MySQLConnection.config() Method</a></dt><dt>MySQLConnection.connect(), <a class="indexterm" href="#connector-python-api-mysqlconnection-connect">MySQLConnection.connect() Method</a></dt><dt>MySQLConnection.cursor(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cursor">MySQLConnection.cursor() Method</a></dt><dt>MySQLConnection.disconnect(), <a class="indexterm" href="#connector-python-api-mysqlconnection-disconnect">MySQLConnection.disconnect() Method</a></dt><dt>MySQLConnection.get_row(), <a class="indexterm" href="#connector-python-api-mysqlconnection-get-row">MySQLConnection.get_row() Method</a></dt><dt>MySQLConnection.get_rows(), <a class="indexterm" href="#connector-python-api-mysqlconnection-get-rows">MySQLConnection.get_rows() Method</a></dt><dt>MySQLConnection.get_server_info(), <a class="indexterm" href="#connector-python-api-mysqlconnection-get-server-info">MySQLConnection.get_server_info() Method</a></dt><dt>MySQLConnection.get_server_version(), <a class="indexterm" href="#connector-python-api-mysqlconnection-get-server-version">MySQLConnection.get_server_version() Method</a></dt><dt>MySQLConnection.isset_client_flag(), <a class="indexterm" href="#connector-python-api-mysqlconnection-isset-client-flag">MySQLConnection.isset_client_flag() Method</a></dt><dt>MySQLConnection.is_connected(), <a class="indexterm" href="#connector-python-api-mysqlconnection-is-connected">MySQLConnection.is_connected() Method</a></dt><dt>MySQLConnection.ping(), <a class="indexterm" href="#connector-python-api-mysqlconnection-ping">MySQLConnection.ping() Method</a></dt><dt>MySQLConnection.reconnect(), <a class="indexterm" href="#connector-python-api-mysqlconnection-reconnect">MySQLConnection.reconnect() Method</a></dt><dt>MySQLConnection.reset_session(), <a class="indexterm" href="#connector-python-api-mysqlconnection-reset-session">MySQLConnection.reset_session() Method</a></dt><dt>MySQLConnection.rollback(), <a class="indexterm" href="#connector-python-api-mysqlconnection-rollback">MySQLConnection.rollback() Method</a></dt><dt>MySQLConnection.set_charset_collation(), <a class="indexterm" href="#connector-python-api-mysqlconnection-set-charset-collation">MySQLConnection.set_charset_collation() Method</a></dt><dt>MySQLConnection.set_client_flags(), <a class="indexterm" href="#connector-python-api-mysqlconnection-set-client-flags">MySQLConnection.set_client_flags() Method</a></dt><dt>MySQLConnection.shutdown(), <a class="indexterm" href="#connector-python-api-mysqlconnection-shutdown">MySQLConnection.shutdown() Method</a></dt><dt>MySQLConnection.start_transaction(), <a class="indexterm" href="#connector-python-api-mysqlconnection-start-transaction">MySQLConnection.start_transaction() Method</a></dt><dt>MySQLConnectionPool.add_connection(), <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-add-connection">MySQLConnectionPool.add_connection() Method</a></dt><dt>MySQLConnectionPool.get_connection(), <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-get-connection">MySQLConnectionPool.get_connection() Method</a></dt><dt>MySQLConnectionPool.set_config(), <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-set-config">MySQLConnectionPool.set_config() Method</a></dt><dt>MySQLCursor.add_attribute(), <a class="indexterm" href="#connector-python-api-mysqlcursor-add-attribute">MySQLCursor.add_attribute() Method</a></dt><dt>MySQLCursor.callproc(), <a class="indexterm" href="#connector-python-api-mysqlcursor-callproc">MySQLCursor.callproc() Method</a></dt><dt>MySQLCursor.clear_attributes(), <a class="indexterm" href="#connector-python-api-mysqlcursor-clear-attributes">MySQLCursor.clear_attributes() Method</a></dt><dt>MySQLCursor.close(), <a class="indexterm" href="#connector-python-api-mysqlcursor-close">MySQLCursor.close() Method</a></dt><dt>MySQLCursor.execute(), <a class="indexterm" href="#connector-python-api-mysqlcursor-execute">MySQLCursor.execute() Method</a></dt><dt>MySQLCursor.executemany(), <a class="indexterm" href="#connector-python-api-mysqlcursor-executemany">MySQLCursor.executemany() Method</a></dt><dt>MySQLCursor.fetchall(), <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchall">MySQLCursor.fetchall() Method</a></dt><dt>MySQLCursor.fetchmany(), <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchmany">MySQLCursor.fetchmany() Method</a></dt><dt>MySQLCursor.fetchone(), <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchone">MySQLCursor.fetchone() Method</a></dt><dt>MySQLCursor.fetchsets(), <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchsets">MySQLCursor.fetchsets() Method</a></dt><dt>MySQLCursor.fetchwarnings(), <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchwarnings">MySQLCursor.fetchwarnings() Method</a></dt><dt>MySQLCursor.get_attributes(), <a class="indexterm" href="#connector-python-api-mysqlcursor-get-attributes">MySQLCursor.get_attributes() Method</a></dt><dt>MySQLCursor.nextset(), <a class="indexterm" href="#connector-python-api-mysqlcursor-nextset">MySQLCursor.nextset() Method</a></dt><dt>MySQLCursor.stored_results(), <a class="indexterm" href="#connector-python-api-mysqlcursor-stored-results">MySQLCursor.stored_results() Method</a></dt><dt>PooledMySQLConnection.close(), <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-close">PooledMySQLConnection.close() Method</a></dt><dt>PooledMySQLConnection.config(), <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-config">PooledMySQLConnection.config() Method</a></dt><dt>_mysql_connector.MySQL.affected_rows(), <a class="indexterm" href="#connector-python-api-cext-affected-rows">_mysql_connector.MySQL.affected_rows() Method</a></dt><dt>_mysql_connector.MySQL.autocommit(), <a class="indexterm" href="#connector-python-api-cext-autocommit">_mysql_connector.MySQL.autocommit() Method</a></dt><dt>_mysql_connector.MySQL.buffered(), <a class="indexterm" href="#connector-python-api-cext-buffered">_mysql_connector.MySQL.buffered() Method</a></dt><dt>_mysql_connector.MySQL.change_user(), <a class="indexterm" href="#connector-python-api-cext-change-user">_mysql_connector.MySQL.change_user() Method</a></dt><dt>_mysql_connector.MySQL.character_set_name(), <a class="indexterm" href="#connector-python-api-cext-character-set-name">_mysql_connector.MySQL.character_set_name() Method</a></dt><dt>_mysql_connector.MySQL.close(), <a class="indexterm" href="#connector-python-api-cext-close">_mysql_connector.MySQL.close() Method</a></dt><dt>_mysql_connector.MySQL.commit(), <a class="indexterm" href="#connector-python-api-cext-commit">_mysql_connector.MySQL.commit() Method</a></dt><dt>_mysql_connector.MySQL.connect(), <a class="indexterm" href="#connector-python-api-cext-connect">_mysql_connector.MySQL.connect() Method</a></dt><dt>_mysql_connector.MySQL.connected(), <a class="indexterm" href="#connector-python-api-cext-connected">_mysql_connector.MySQL.connected() Method</a></dt><dt>_mysql_connector.MySQL.consume_result(), <a class="indexterm" href="#connector-python-api-cext-consume-result">_mysql_connector.MySQL.consume_result() Method</a></dt><dt>_mysql_connector.MySQL.convert_to_mysql(), <a class="indexterm" href="#connector-python-api-cext-convert-to-mysql">_mysql_connector.MySQL.convert_to_mysql() Method</a></dt><dt>_mysql_connector.MySQL.escape_string(), <a class="indexterm" href="#connector-python-api-cext-escape-string">_mysql_connector.MySQL.escape_string() Method</a></dt><dt>_mysql_connector.MySQL.fetch_fields(), <a class="indexterm" href="#connector-python-api-cext-fetch-fields">_mysql_connector.MySQL.fetch_fields() Method</a></dt><dt>_mysql_connector.MySQL.fetch_row(), <a class="indexterm" href="#connector-python-api-cext-fetch-row">_mysql_connector.MySQL.fetch_row() Method</a></dt><dt>_mysql_connector.MySQL.field_count(), <a class="indexterm" href="#connector-python-api-cext-field-count">_mysql_connector.MySQL.field_count() Method</a></dt><dt>_mysql_connector.MySQL.free_result(), <a class="indexterm" href="#connector-python-api-cext-free-result">_mysql_connector.MySQL.free_result() Method</a></dt><dt>_mysql_connector.MySQL.get_character_set_info(), <a class="indexterm" href="#connector-python-api-cext-get-character-set-info">_mysql_connector.MySQL.get_character_set_info() Method</a></dt><dt>_mysql_connector.MySQL.get_client_info(), <a class="indexterm" href="#connector-python-api-cext-get-client-info">_mysql_connector.MySQL.get_client_info() Method</a></dt><dt>_mysql_connector.MySQL.get_client_version(), <a class="indexterm" href="#connector-python-api-cext-get-client-version">_mysql_connector.MySQL.get_client_version() Method</a></dt><dt>_mysql_connector.MySQL.get_host_info(), <a class="indexterm" href="#connector-python-api-cext-get-host-info">_mysql_connector.MySQL.get_host_info() Method</a></dt><dt>_mysql_connector.MySQL.get_proto_info(), <a class="indexterm" href="#connector-python-api-cext-get-proto-info">_mysql_connector.MySQL.get_proto_info() Method</a></dt><dt>_mysql_connector.MySQL.get_server_info(), <a class="indexterm" href="#connector-python-api-cext-get-server-info">_mysql_connector.MySQL.get_server_info() Method</a></dt><dt>_mysql_connector.MySQL.get_server_version(), <a class="indexterm" href="#connector-python-api-cext-get-server-version">_mysql_connector.MySQL.get_server_version() Method</a></dt><dt>_mysql_connector.MySQL.get_ssl_cipher(), <a class="indexterm" href="#connector-python-api-cext-get-ssl-cipher">_mysql_connector.MySQL.get_ssl_cipher() Method</a></dt><dt>_mysql_connector.MySQL.hex_string(), <a class="indexterm" href="#connector-python-api-cext-hex-string">_mysql_connector.MySQL.hex_string() Method</a></dt><dt>_mysql_connector.MySQL.insert_id(), <a class="indexterm" href="#connector-python-api-cext-insert-id">_mysql_connector.MySQL.insert_id() Method</a></dt><dt>_mysql_connector.MySQL.more_results(), <a class="indexterm" href="#connector-python-api-cext-more-results">_mysql_connector.MySQL.more_results() Method</a></dt><dt>_mysql_connector.MySQL.next_result(), <a class="indexterm" href="#connector-python-api-cext-next-result">_mysql_connector.MySQL.next_result() Method</a></dt><dt>_mysql_connector.MySQL.num_fields(), <a class="indexterm" href="#connector-python-api-cext-num-fields">_mysql_connector.MySQL.num_fields() Method</a></dt><dt>_mysql_connector.MySQL.num_rows(), <a class="indexterm" href="#connector-python-api-cext-num-rows">_mysql_connector.MySQL.num_rows() Method</a></dt><dt>_mysql_connector.MySQL.ping(), <a class="indexterm" href="#connector-python-api-cext-ping">_mysql_connector.MySQL.ping() Method</a></dt><dt>_mysql_connector.MySQL.query(), <a class="indexterm" href="#connector-python-api-cext-query">_mysql_connector.MySQL.query() Method</a></dt><dt>_mysql_connector.MySQL.raw(), <a class="indexterm" href="#connector-python-api-cext-raw">_mysql_connector.MySQL.raw() Method</a></dt><dt>_mysql_connector.MySQL.refresh(), <a class="indexterm" href="#connector-python-api-cext-refresh">_mysql_connector.MySQL.refresh() Method</a></dt><dt>_mysql_connector.MySQL.reset_connection(), <a class="indexterm" href="#connector-python-api-cext-reset-connection">_mysql_connector.MySQL.reset_connection() Method</a></dt><dt>_mysql_connector.MySQL.rollback(), <a class="indexterm" href="#connector-python-api-cext-rollback">_mysql_connector.MySQL.rollback() Method</a></dt><dt>_mysql_connector.MySQL.select_db(), <a class="indexterm" href="#connector-python-api-cext-select-db">_mysql_connector.MySQL.select_db() Method</a></dt><dt>_mysql_connector.MySQL.set_character_set(), <a class="indexterm" href="#connector-python-api-cext-set-character-set">_mysql_connector.MySQL.set_character_set() Method</a></dt><dt>_mysql_connector.MySQL.shutdown(), <a class="indexterm" href="#connector-python-api-cext-shutdown">_mysql_connector.MySQL.shutdown() Method</a></dt><dt>_mysql_connector.MySQL.stat(), <a class="indexterm" href="#connector-python-api-cext-stat">_mysql_connector.MySQL.stat() Method</a></dt><dt>_mysql_connector.MySQL.thread_id(), <a class="indexterm" href="#connector-python-api-cext-thread-id">_mysql_connector.MySQL.thread_id() Method</a></dt><dt>_mysql_connector.MySQL.use_unicode(), <a class="indexterm" href="#connector-python-api-cext-use-unicode">_mysql_connector.MySQL.use_unicode() Method</a></dt><dt>_mysql_connector.MySQL.warning_count(), <a class="indexterm" href="#connector-python-api-cext-warning-count">_mysql_connector.MySQL.warning_count() Method</a></dt></dl></dd><dt id="ientry-id3318">module</dt><dd><dl><dt>errorcode, <a class="indexterm" href="#connector-python-api-errorcode">errorcode Module</a></dt><dt>mysql.connector, <a class="indexterm" href="#connector-python-api-mysql-connector">mysql.connector Module</a></dt><dt>_mysql_connector, <a class="indexterm" href="#connector-python-api-cext-mysql-connector">_mysql_connector Module</a></dt></dl></dd><dt id="ientry-id3316">mysql.connector module, <a class="indexterm" href="#connector-python-api-mysql-connector">mysql.connector Module</a></dt><dt id="ientry-id3338">mysql.connector.apilevel property, <a class="indexterm" href="#connector-python-api-mysql-connector-apilevel">mysql.connector.apilevel Property</a></dt><dt id="ientry-id3324">mysql.connector.connect() method, <a class="indexterm" href="#connector-python-api-mysql-connector-connect">mysql.connector.connect() Method</a></dt><dt id="ientry-id3346">mysql.connector.paramstyle property, <a class="indexterm" href="#connector-python-api-mysql-connector-paramstyle">mysql.connector.paramstyle Property</a></dt><dt id="ientry-id3354">mysql.connector.threadsafety property, <a class="indexterm" href="#connector-python-api-mysql-connector-threadsafety">mysql.connector.threadsafety Property</a></dt><dt id="ientry-id3370">mysql.connector.__version_info__ property, <a class="indexterm" href="#connector-python-api-mysql-connector-version-info">mysql.connector.__version_info__ Property</a></dt><dt id="ientry-id3362">mysql.connector.__version__ property, <a class="indexterm" href="#connector-python-api-mysql-connector-version">mysql.connector.__version__ Property</a></dt><dt id="ientry-id3977">MySQLConnection.autocommit property, <a class="indexterm" href="#connector-python-api-mysqlconnection-autocommit">MySQLConnection.autocommit Property</a></dt><dt id="ientry-id4005">MySQLConnection.can_consume_results property, <a class="indexterm" href="#connector-python-api-mysqlconnection-can-consume-results">MySQLConnection.can_consume_results Property</a></dt><dt id="ientry-id4015">MySQLConnection.charset property, <a class="indexterm" href="#connector-python-api-mysqlconnection-charset">MySQLConnection.charset Property</a></dt><dt id="ientry-id4022">MySQLConnection.client_flags property, <a class="indexterm" href="#connector-python-api-mysqlconnection-client-flags">MySQLConnection.client_flags Property</a></dt><dt id="ientry-id3398">MySQLConnection.close() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-close">MySQLConnection.close() Method</a></dt><dt id="ientry-id3532">MySQLConnection.cmd_change_user() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-change-user">MySQLConnection.cmd_change_user() Method</a></dt><dt id="ientry-id3546">MySQLConnection.cmd_debug() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-debug">MySQLConnection.cmd_debug() Method</a></dt><dt id="ientry-id3556">MySQLConnection.cmd_init_db() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-init-db">MySQLConnection.cmd_init_db() Method</a></dt><dt id="ientry-id3566">MySQLConnection.cmd_ping() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-ping">MySQLConnection.cmd_ping() Method</a></dt><dt id="ientry-id3577">MySQLConnection.cmd_process_info() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-process-info">MySQLConnection.cmd_process_info() Method</a></dt><dt id="ientry-id3589">MySQLConnection.cmd_process_kill() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-process-kill">MySQLConnection.cmd_process_kill() Method</a></dt><dt id="ientry-id3606">MySQLConnection.cmd_query() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-query">MySQLConnection.cmd_query() Method</a></dt><dt id="ientry-id3623">MySQLConnection.cmd_query_iter() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-query-iter">MySQLConnection.cmd_query_iter() Method</a></dt><dt id="ientry-id3637">MySQLConnection.cmd_quit() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-quit">MySQLConnection.cmd_quit() Method</a></dt><dt id="ientry-id3645">MySQLConnection.cmd_refresh() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-refresh">MySQLConnection.cmd_refresh() Method</a></dt><dt id="ientry-id3665">MySQLConnection.cmd_reset_connection() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-reset-connection">MySQLConnection.cmd_reset_connection() Method</a></dt><dt id="ientry-id3680">MySQLConnection.cmd_shutdown() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-shutdown">MySQLConnection.cmd_shutdown() Method</a></dt><dt id="ientry-id3692">MySQLConnection.cmd_statistics() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-statistics">MySQLConnection.cmd_statistics() Method</a></dt><dt id="ientry-id4040">MySQLConnection.collation property, <a class="indexterm" href="#connector-python-api-mysqlconnection-collation">MySQLConnection.collation Property</a></dt><dt id="ientry-id3413">MySQLConnection.commit() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-commit">MySQLConnection.commit() Method</a></dt><dt id="ientry-id3424">MySQLConnection.config() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-config">MySQLConnection.config() Method</a></dt><dt id="ientry-id3448">MySQLConnection.connect() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-connect">MySQLConnection.connect() Method</a></dt><dt id="ientry-id4047">MySQLConnection.connected property, <a class="indexterm" href="#connector-python-api-mysqlconnection-connected">MySQLConnection.connected Property</a></dt><dt id="ientry-id4060">MySQLConnection.connection_id property, <a class="indexterm" href="#connector-python-api-mysqlconnection-connection-id">MySQLConnection.connection_id Property</a></dt><dt id="ientry-id4068">MySQLConnection.converter-class property, <a class="indexterm" href="#connector-python-api-mysqlconnection-converter-class">MySQLConnection.converter-class Property</a></dt><dt id="ientry-id3468">MySQLConnection.cursor() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cursor">MySQLConnection.cursor() Method</a></dt><dt id="ientry-id4076">MySQLConnection.database property, <a class="indexterm" href="#connector-python-api-mysqlconnection-database">MySQLConnection.database Property</a></dt><dt id="ientry-id3699">MySQLConnection.disconnect() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-disconnect">MySQLConnection.disconnect() Method</a></dt><dt id="ientry-id3713">MySQLConnection.get_row() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-row">MySQLConnection.get_row() Method</a></dt><dt id="ientry-id3734">MySQLConnection.get_rows() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-rows">MySQLConnection.get_rows() Method</a></dt><dt id="ientry-id3759">MySQLConnection.get_server_info() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-server-info">MySQLConnection.get_server_info() Method</a></dt><dt id="ientry-id3772">MySQLConnection.get_server_version() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-server-version">MySQLConnection.get_server_version() Method</a></dt><dt id="ientry-id4086">MySQLConnection.get_warnings property, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-warnings">MySQLConnection.get_warnings Property</a></dt><dt id="ientry-id4102">MySQLConnection.in_transaction property, <a class="indexterm" href="#connector-python-api-mysqlconnection-in-transaction">MySQLConnection.in_transaction Property</a></dt><dt id="ientry-id3801">MySQLConnection.isset_client_flag() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-isset-client-flag">MySQLConnection.isset_client_flag() Method</a></dt><dt id="ientry-id3784">MySQLConnection.is_connected() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-is-connected">MySQLConnection.is_connected() Method</a></dt><dt id="ientry-id3812">MySQLConnection.ping() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-ping">MySQLConnection.ping() Method</a></dt><dt id="ientry-id4121">MySQLConnection.raise_on_warnings property, <a class="indexterm" href="#connector-python-api-mysqlconnection-raise-on-warnings">MySQLConnection.raise_on_warnings Property</a></dt><dt id="ientry-id3832">MySQLConnection.reconnect() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-reconnect">MySQLConnection.reconnect() Method</a></dt><dt id="ientry-id3845">MySQLConnection.reset_session() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-reset-session">MySQLConnection.reset_session() Method</a></dt><dt id="ientry-id3862">MySQLConnection.rollback() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-rollback">MySQLConnection.rollback() Method</a></dt><dt id="ientry-id4142">MySQLConnection.server_host property, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-host">MySQLConnection.server_host Property</a></dt><dt id="ientry-id4150">MySQLConnection.server_info property, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-info">MySQLConnection.server_info Property</a></dt><dt id="ientry-id4159">MySQLConnection.server_port property, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-port">MySQLConnection.server_port Property</a></dt><dt id="ientry-id4167">MySQLConnection.server_version property, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-version">MySQLConnection.server_version Property</a></dt><dt id="ientry-id3875">MySQLConnection.set_charset_collation() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-set-charset-collation">MySQLConnection.set_charset_collation() Method</a></dt><dt id="ientry-id3896">MySQLConnection.set_client_flags() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-set-client-flags">MySQLConnection.set_client_flags() Method</a></dt><dt id="ientry-id3918">MySQLConnection.shutdown() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-shutdown">MySQLConnection.shutdown() Method</a></dt><dt id="ientry-id4175">MySQLConnection.sql_mode property, <a class="indexterm" href="#connector-python-api-mysqlconnection-sql-mode">MySQLConnection.sql_mode Property</a></dt><dt id="ientry-id3932">MySQLConnection.start_transaction() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-start-transaction">MySQLConnection.start_transaction() Method</a></dt><dt id="ientry-id4186">MySQLConnection.time_zone property, <a class="indexterm" href="#connector-python-api-mysqlconnection-time-zone">MySQLConnection.time_zone Property</a></dt><dt id="ientry-id4205">MySQLConnection.unix_socket property, <a class="indexterm" href="#connector-python-api-mysqlconnection-unix-socket">MySQLConnection.unix_socket Property</a></dt><dt id="ientry-id3995">MySQLConnection.unread_results property, <a class="indexterm" href="#connector-python-api-mysqlconnection-unread-results">MySQLConnection.unread_results Property</a></dt><dt id="ientry-id4213">MySQLConnection.user property, <a class="indexterm" href="#connector-python-api-mysqlconnection-user">MySQLConnection.user Property</a></dt><dt id="ientry-id4195">MySQLConnection.use_unicode property, <a class="indexterm" href="#connector-python-api-mysqlconnection-use-unicode">MySQLConnection.use_unicode Property</a></dt><dt id="ientry-id4261">MySQLConnectionPool.add_connection() method, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-add-connection">MySQLConnectionPool.add_connection() Method</a></dt><dt id="ientry-id4280">MySQLConnectionPool.get_connection() method, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-get-connection">MySQLConnectionPool.get_connection() Method</a></dt><dt id="ientry-id4309">MySQLConnectionPool.pool_name property, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-pool-name">MySQLConnectionPool.pool_name Property</a></dt><dt id="ientry-id4292">MySQLConnectionPool.set_config() method, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-set-config">MySQLConnectionPool.set_config() Method</a></dt><dt id="ientry-id4461">MySQLCursor.add_attribute() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-add-attribute">MySQLCursor.add_attribute() Method</a></dt><dt id="ientry-id4502">MySQLCursor.callproc() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-callproc">MySQLCursor.callproc() Method</a></dt><dt id="ientry-id4480">MySQLCursor.clear_attributes() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-clear-attributes">MySQLCursor.clear_attributes() Method</a></dt><dt id="ientry-id4529">MySQLCursor.close() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-close">MySQLCursor.close() Method</a></dt><dt id="ientry-id4709">MySQLCursor.column_names property, <a class="indexterm" href="#connector-python-api-mysqlcursor-column-names">MySQLCursor.column_names Property</a></dt><dt id="ientry-id4723">MySQLCursor.description property, <a class="indexterm" href="#connector-python-api-mysqlcursor-description">MySQLCursor.description Property</a></dt><dt id="ientry-id4539">MySQLCursor.execute() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-execute">MySQLCursor.execute() Method</a></dt><dt id="ientry-id4572">MySQLCursor.executemany() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-executemany">MySQLCursor.executemany() Method</a></dt><dt id="ientry-id4601">MySQLCursor.fetchall() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchall">MySQLCursor.fetchall() Method</a></dt><dt id="ientry-id4613">MySQLCursor.fetchmany() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchmany">MySQLCursor.fetchmany() Method</a></dt><dt id="ientry-id4625">MySQLCursor.fetchone() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchone">MySQLCursor.fetchone() Method</a></dt><dt id="ientry-id4659">MySQLCursor.fetchsets() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchsets">MySQLCursor.fetchsets() Method</a></dt><dt id="ientry-id4671">MySQLCursor.fetchwarnings() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchwarnings">MySQLCursor.fetchwarnings() Method</a></dt><dt id="ientry-id4491">MySQLCursor.get_attributes() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-get-attributes">MySQLCursor.get_attributes() Method</a></dt><dt id="ientry-id4760">MySQLCursor.lastrowid property, <a class="indexterm" href="#connector-python-api-mysqlcursor-lastrowid">MySQLCursor.lastrowid Property</a></dt><dt id="ientry-id4645">MySQLCursor.nextset() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-nextset">MySQLCursor.nextset() Method</a></dt><dt id="ientry-id4786">MySQLCursor.rowcount property, <a class="indexterm" href="#connector-python-api-mysqlcursor-rowcount">MySQLCursor.rowcount Property</a></dt><dt id="ientry-id4808">MySQLCursor.statement property, <a class="indexterm" href="#connector-python-api-mysqlcursor-statement">MySQLCursor.statement Property</a></dt><dt id="ientry-id4693">MySQLCursor.stored_results() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-stored-results">MySQLCursor.stored_results() Method</a></dt><dt id="ientry-id4742">MySQLCursor.warnings property, <a class="indexterm" href="#connector-python-api-mysqlcursor-warnings">MySQLCursor.warnings Property</a></dt><dt id="ientry-id4824">MySQLCursor.with_rows property, <a class="indexterm" href="#connector-python-api-mysqlcursor-with-rows">MySQLCursor.with_rows Property</a></dt></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_P"></a>P</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id1569">PEP 249, <a class="indexterm" href="#connector-python-introduction">Introduction to MySQL Connector/Python</a></dt><dt id="ientry-id4367">PooledMySQLConnection.close() method, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-close">PooledMySQLConnection.close() Method</a></dt><dt id="ientry-id4379">PooledMySQLConnection.config() method, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-config">PooledMySQLConnection.config() Method</a></dt><dt id="ientry-id4388">PooledMySQLConnection.pool_name property, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-pool-name">PooledMySQLConnection.pool_name Property</a></dt><dt id="ientry-id4221">pooling.MySQLConnectionPool class, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool">pooling.MySQLConnectionPool Class</a></dt><dt id="ientry-id4228">pooling.MySQLConnectionPool constructor, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-constructor">pooling.MySQLConnectionPool Constructor</a></dt><dt id="ientry-id4320">pooling.PooledMySQLConnection class, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection">pooling.PooledMySQLConnection Class</a></dt><dt id="ientry-id4345">pooling.PooledMySQLConnection constructor, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-constructor">pooling.PooledMySQLConnection Constructor</a></dt><dt id="ientry-id4941">prepared statements, <a class="indexterm" href="#connector-python-api-mysqlcursorprepared">cursor.MySQLCursorPrepared Class</a></dt><dt id="ientry-id3340">property</dt><dd><dl><dt>mysql.connector.apilevel, <a class="indexterm" href="#connector-python-api-mysql-connector-apilevel">mysql.connector.apilevel Property</a></dt><dt>mysql.connector.paramstyle, <a class="indexterm" href="#connector-python-api-mysql-connector-paramstyle">mysql.connector.paramstyle Property</a></dt><dt>mysql.connector.threadsafety, <a class="indexterm" href="#connector-python-api-mysql-connector-threadsafety">mysql.connector.threadsafety Property</a></dt><dt>mysql.connector.__version_info__, <a class="indexterm" href="#connector-python-api-mysql-connector-version-info">mysql.connector.__version_info__ Property</a></dt><dt>mysql.connector.__version__, <a class="indexterm" href="#connector-python-api-mysql-connector-version">mysql.connector.__version__ Property</a></dt><dt>MySQLConnection.autocommit, <a class="indexterm" href="#connector-python-api-mysqlconnection-autocommit">MySQLConnection.autocommit Property</a></dt><dt>MySQLConnection.can_consume_results, <a class="indexterm" href="#connector-python-api-mysqlconnection-can-consume-results">MySQLConnection.can_consume_results Property</a></dt><dt>MySQLConnection.charset, <a class="indexterm" href="#connector-python-api-mysqlconnection-charset">MySQLConnection.charset Property</a></dt><dt>MySQLConnection.client_flags, <a class="indexterm" href="#connector-python-api-mysqlconnection-client-flags">MySQLConnection.client_flags Property</a></dt><dt>MySQLConnection.collation, <a class="indexterm" href="#connector-python-api-mysqlconnection-collation">MySQLConnection.collation Property</a></dt><dt>MySQLConnection.connected, <a class="indexterm" href="#connector-python-api-mysqlconnection-connected">MySQLConnection.connected Property</a></dt><dt>MySQLConnection.connection_id, <a class="indexterm" href="#connector-python-api-mysqlconnection-connection-id">MySQLConnection.connection_id Property</a></dt><dt>MySQLConnection.converter-class, <a class="indexterm" href="#connector-python-api-mysqlconnection-converter-class">MySQLConnection.converter-class Property</a></dt><dt>MySQLConnection.database, <a class="indexterm" href="#connector-python-api-mysqlconnection-database">MySQLConnection.database Property</a></dt><dt>MySQLConnection.get_warnings, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-warnings">MySQLConnection.get_warnings Property</a></dt><dt>MySQLConnection.in_transaction, <a class="indexterm" href="#connector-python-api-mysqlconnection-in-transaction">MySQLConnection.in_transaction Property</a></dt><dt>MySQLConnection.raise_on_warnings, <a class="indexterm" href="#connector-python-api-mysqlconnection-raise-on-warnings">MySQLConnection.raise_on_warnings Property</a></dt><dt>MySQLConnection.server_host, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-host">MySQLConnection.server_host Property</a></dt><dt>MySQLConnection.server_info, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-info">MySQLConnection.server_info Property</a></dt><dt>MySQLConnection.server_port, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-port">MySQLConnection.server_port Property</a></dt><dt>MySQLConnection.server_version, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-version">MySQLConnection.server_version Property</a></dt><dt>MySQLConnection.sql_mode, <a class="indexterm" href="#connector-python-api-mysqlconnection-sql-mode">MySQLConnection.sql_mode Property</a></dt><dt>MySQLConnection.time_zone, <a class="indexterm" href="#connector-python-api-mysqlconnection-time-zone">MySQLConnection.time_zone Property</a></dt><dt>MySQLConnection.unix_socket, <a class="indexterm" href="#connector-python-api-mysqlconnection-unix-socket">MySQLConnection.unix_socket Property</a></dt><dt>MySQLConnection.unread_results, <a class="indexterm" href="#connector-python-api-mysqlconnection-unread-results">MySQLConnection.unread_results Property</a></dt><dt>MySQLConnection.user, <a class="indexterm" href="#connector-python-api-mysqlconnection-user">MySQLConnection.user Property</a></dt><dt>MySQLConnection.use_unicode, <a class="indexterm" href="#connector-python-api-mysqlconnection-use-unicode">MySQLConnection.use_unicode Property</a></dt><dt>MySQLConnectionPool.pool_name, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-pool-name">MySQLConnectionPool.pool_name Property</a></dt><dt>MySQLCursor.column_names, <a class="indexterm" href="#connector-python-api-mysqlcursor-column-names">MySQLCursor.column_names Property</a></dt><dt>MySQLCursor.description, <a class="indexterm" href="#connector-python-api-mysqlcursor-description">MySQLCursor.description Property</a></dt><dt>MySQLCursor.lastrowid, <a class="indexterm" href="#connector-python-api-mysqlcursor-lastrowid">MySQLCursor.lastrowid Property</a></dt><dt>MySQLCursor.rowcount, <a class="indexterm" href="#connector-python-api-mysqlcursor-rowcount">MySQLCursor.rowcount Property</a></dt><dt>MySQLCursor.statement, <a class="indexterm" href="#connector-python-api-mysqlcursor-statement">MySQLCursor.statement Property</a></dt><dt>MySQLCursor.warnings, <a class="indexterm" href="#connector-python-api-mysqlcursor-warnings">MySQLCursor.warnings Property</a></dt><dt>MySQLCursor.with_rows, <a class="indexterm" href="#connector-python-api-mysqlcursor-with-rows">MySQLCursor.with_rows Property</a></dt><dt>PooledMySQLConnection.pool_name, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-pool-name">PooledMySQLConnection.pool_name Property</a></dt><dt>_mysql_connector.MySQL.have_result_set, <a class="indexterm" href="#connector-python-api-cext-have-result-set">_mysql_connector.MySQL.have_result_set Property</a></dt></dl></dd><dt id="ientry-id1573">Python, <a class="indexterm" href="#connector-python-introduction">Introduction to MySQL Connector/Python</a></dt><dt id="ientry-id1567">Python Database API Specification v2.0 (PEP 249), <a class="indexterm" href="#connector-python-introduction">Introduction to MySQL Connector/Python</a></dt></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_S"></a>S</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id4842">Subclasses cursor.mysqlcursor, <a class="indexterm" href="#connector-python-api-cursor-subclasses">Subclasses cursor.MySQLCursor</a></dt></dl></div></div></div></div><div class="copyright-footer"></div></body></html>