Table of Contents
This chapter contains the public API reference for the Connector/Python C
Extension, also known as the _mysql_connector
Python module.
The _mysql_connector C Extension module can be
used directly without any other code of Connector/Python. One reason to use
this module directly is for performance reasons.
Examples in this reference use ccnx to
represent a connector object as used with the
_mysql_connector C Extension module.
ccnx is an instance of the
_mysql_connector.MySQL() class. It is distinct
from the cnx object used in examples for the
mysql.connector Connector/Python module described in
Chapter 10, Connector/Python API Reference.
cnx is an instance of the object returned by
the connect() method of the
MySQLConnection class.
The C Extension is not part of the pure Python installation. It is an optional module that must be installed using a binary distribution of Connector/Python that includes it, or compiled using a source distribution. See Chapter 4, Connector/Python Installation.
Syntax:
ccnx = _mysql_connector.MySQL(args)
The MySQL class is used to open and manage a
connection to a MySQL server (referred to elsewhere in this
reference as “the MySQL
instance”). It is also used to send commands and SQL
statements and read results.
The MySQL class wraps most functions found in
the MySQL C Client API and adds some additional convenient
functionality.
import _mysql_connector
ccnx = _mysql_connector.MySQL()
ccnx.connect(user='scott', password='tiger',
host='127.0.0.1', database='employees')
ccnx.close()
Permitted arguments for the MySQL class are
auth_plugin, buffered,
charset_name,
connection_timeout, raw,
use_unicode. Those arguments correspond to the
arguments of the same names for
MySQLConnection.connect() as described at
Section 7.1, “Connector/Python Connection Arguments”, except that
charset_name corresponds to
charset.
Syntax:
count = ccnx.afffected_rows()
Returns the number of rows changed, inserted, or deleted by the
most recent UPDATE,
INSERT, or
DELETE statement.
Syntax:
ccnx.autocommit(bool)
Sets the autocommit mode.
Raises a ValueError exception if
mode is not True or
False.
Syntax:
is_buffered = ccnx.buffered() # getter
ccnx.buffered(bool) # setter
With no argument, returns True or
False to indicate whether the
MySQL instance buffers (stores) the results.
With a boolean argument, sets the MySQL
instance buffering mode.
For the setter syntax, raises a TypeError
exception if the value is not True or
False.
Syntax:
ccnx.change_user(user='user_name, password='password_val', database='db_name')
Changes the user and sets a new default database. Permitted
arguments are user,
password, and database.
Syntax:
charset = ccnx.character_set_name()
Returns the name of the default character set for the current MySQL session.
Some MySQL character sets have no equivalent names in Python. When
this is the case, a name usable by Python is returned. For
example, the 'utf8mb4' MySQL character set name
is returned as 'utf8'.
Syntax:
ccnx.connect(args)
Connects to a MySQL server.
import _mysql_connector
ccnx = _mysql_connector.MySQL()
ccnx.connect(user='scott', password='tiger',
host='127.0.0.1', database='employees')
ccnx.close()
connect() supports the following arguments:
host, user,
password, database,
port, unix_socket,
client_flags, ssl_ca,
ssl_cert, ssl_key,
ssl_verify_cert, compress.
See Section 7.1, “Connector/Python Connection Arguments”.
If ccnx is already connected,
connect() discards any pending result set and
closes the connection before reopening it.
Raises a TypeError exception if any argument is
of an invalid type.
Syntax:
is_connected = ccnx.connected()
Returns True or False to
indicate whether the MySQL instance is
connected.
Syntax:
ccnx.consume_result()
Consumes the stored result set, if there is one, for this
MySQL instance, by fetching all rows. If the
statement that was executed returned multiple result sets, this
method loops over and consumes all of them.
Syntax:
converted_obj = ccnx.convert_to_mysql(obj))
Converts a Python object to a MySQL value based on the Python type of the object. The converted object is escaped and quoted.
ccnx.query('SELECT CURRENT_USER(), 1 + 3, NOW()')
row = ccnx.fetch_row()
for col in row:
print(ccnx.convert_to_mysql(col))
ccnx.consume_result()
Raises a MySQLInterfaceError exception if the
Python object cannot be converted.
Syntax:
str = ccnx.escape_string(str_to_escape)
Uses the mysql_escape_string() C
API function to create a SQL string that you can use in an SQL
statement.
Raises a TypeError exception if the value does
not have a Unicode, bytes,
or (for Python 2) string type. Raises a
MySQLError exception if the string could not be
escaped.
Syntax:
field_info = ccnx.fetch_fields()
Fetches column information for the active result set. Returns a list of tuples, one tuple per column
Raises a MySQLInterfaceError exception for any
MySQL error returned by the MySQL server.
ccnx.query('SELECT CURRENT_USER(), 1 + 3, NOW()')
field_info = ccnx.fetch_fields()
for fi in field_info:
print(fi)
ccnx.consume_result()
Syntax:
row = ccnx.fetch_row()
Fetches the next row from the active result set. The row is
returned as a tuple that contains the values converted to Python
objects, unless raw was set.
ccnx.query('SELECT CURRENT_USER(), 1 + 3, NOW()')
row = ccnx.fetch_row()
print(row)
ccnx.free_result()
Raises a MySQLInterfaceError exception for any
MySQL error returned by the MySQL server.
Syntax:
ccnx.free_result()
Frees the stored result set, if there is one, for this
MySQL instance. If the statement that was
executed returned multiple result sets, this method loops over and
consumes all of them.
Syntax:
info = ccnx.get_character_set_info()
Returns information about the default character set for the
current MySQL session. The returned dictionary has the keys
number, name,
csname, comment,
dir, mbminlen, and
mbmaxlen.
Syntax:
info = ccnx.get_host_info()
Returns a description of the type of connection in use as a string.
Syntax:
info = ccnx.get_ssl_cipher()
Returns the SSL cipher used for the current session, or
None if SSL is not in use.
Syntax:
str = ccnx.hex_string(string_to_hexify)
Encodes a value in hexadecimal format and wraps it within
X''. For example, "ham"
becomes X'68616D'.
Syntax:
insert_id = ccnx.insert_id()
Returns the AUTO_INCREMENT value generated by
the most recent executed statement, or 0 if there is no such
value.
Syntax:
more = ccnx.more_results()
Returns True or False to
indicate whether any more result sets exist.
Syntax:
ccnx.next_result()
Initiates the next result set for a statement string that produced multiple result sets.
Raises a MySQLInterfaceError exception for any
MySQL error returned by the MySQL server.
Syntax:
count = ccnx.num_rows()
Returns the number of rows in the active result set.
Raises a MySQLError exception if there is no
result set.
Syntax:
alive = ccnx.ping()
Returns True or False to
indicate whether the connection to the MySQL server is working.
Syntax:
ccnx.query(args)
Executes an SQL statement. The permitted arguments are
statement, buffered,
raw, and raw_as_string.
ccnx.query('DROP TABLE IF EXISTS t')
ccnx.query('CREATE TABLE t (i INT NOT NULL AUTO_INCREMENT PRIMARY KEY)')
ccnx.query('INSERT INTO t (i) VALUES (NULL),(NULL),(NULL)')
ccnx.query('SELECT LAST_INSERT_ID()')
row = ccnx.fetch_row()
print('LAST_INSERT_ID(): ', row)
ccnx.consume_result()
buffered and raw, if not
provided, take their values from the MySQL
instance. raw_as_string is a special argument
for Python v2 and returns str instead of
bytearray (compatible with Connector/Python
v1.x).
To check whether the query returns rows, check the
have_result_set property of the
MySQL instance.
query() returns True if the
query executes, and raises an exception otherwise. It raises a
TypeError exception if any argument has an
invalid type, and a MySQLInterfaceError
exception for any MySQL error returned by the MySQL server.
Syntax:
is_raw = ccnx.raw() # getter
ccnx.raw(bool) # setter
With no argument, returns True or
False to indicate whether the
MySQL instance return the rows as is (without
conversion to Python objects).
With a boolean argument, sets the MySQL
instance raw mode.
Syntax:
ccnx.refresh(flags)
Flushes or resets the tables and caches indicated by the argument. The only argument currently permitted is an integer.
Raises a TypeError exception if the first
argument is not an integer.
Syntax:
ccnx.rollback()
Rolls back the current transaction.
Raises a MySQLInterfaceError exception on
errors.
Syntax:
ccnx.select_db(db_name)
Sets the default (current) database for the current session.
Raises a MySQLInterfaceError exception for any
MySQL error returned by the MySQL server.
Syntax:
ccnx.set_character_set(charset_name)
Sets the default character set for the current session. The only argument permitted is a string that contains the character set name.
Raises a TypeError exception if the argument is
not a PyString_type.
Syntax:
ccnx.shutdown(flags)
Shuts down the MySQL server. The only argument currently permitted is an integer that describes the shutdown type.
Raises a TypeError exception if the first
argument is not an integer. Raises a
MySQLErrorInterface exception if an error is
retured by the MySQL server.
Syntax:
info = ccnx.stat()
Returns the server status as a string.
Raises a MySQLErrorInterface exception if an
error is retured by the MySQL server.
Syntax:
is_unicode = ccnx.use_unicode() # getter
ccnx.use_unicode(bool) # setter
With no argument, returns True or
False to indicate whether the
MySQL instance returns nonbinary strings as
Unicode.
With a boolean argument, sets whether the MySQL
instance returns nonbinary strings as Unicode.