The MySQLConnection class is used to open and manage a connection to a MySQL server. It also used to send commands and SQL statements and read the results.
The MySQLConnection constructor initializes the attributes and when at least one argument is passed, it tries to connect with the MySQL server.
For a complete list or arguments, see Section 22.6.6, “Connector/Python Connection Arguments”.
Configures a MySQLConnection instance after it has been instantiated. For a complete list of possible arguments, see Section 22.6.6, “Connector/Python Connection Arguments”.
You could use the config() method to change
(for example) the user name, then call
reconnect().
cnx = MySQLConnection(user='joe', database='test') # Connected as 'joe' cnx.config(user='jane') cnx.reconnect() # Now connected as 'jane'
This method sets up a connection, establishing a session with the MySQL server. If no arguments are given, it uses the already configured or default values. For a complete list of possible arguments, see Section 22.6.6, “Connector/Python Connection Arguments”.
This method sends a COMMIT statement to the
MySQL server, committing the current transaction. Since by
default Connector/Python does not autocommit, it is important to
call this method after every transaction that modifies data for
tables that use transactional storage engines.
>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)", ('Jane'))
>>> cnx.commit()
To roll back instead and discard modifications, see the rollback() method.
This method returns a MySQLCursor() object,
or a subclass of it depending on the passed arguments.
When buffered is True, the
cursor fetches all rows after the operation is executed. This is
useful when queries return small result sets. Setting
raw skips the conversion from MySQL data
types to Python types when fetching rows. Raw is usually used
when you want to get better performance or you want to do the
conversion yourself.
The cursor_class argument can be used to pass
a class to use for instantiating a new cursor. It must be a
subclass of cursor.CursorBase.
The returned object depends on the combination of the
buffered and raw
arguments.
If not buffered and not raw:
cursor.MySQLCursor
If buffered and not raw:
cursor.MySQLCursorBuffered
If buffered and raw:
cursor.MySQLCursorBufferedRaw
If not buffered and raw:
cursor.MySQLCursorRaw
Returns a CursorBase instance.
Changes the user using username and
password. It also causes the specified
database to become the default (current)
database. It is also possible to change the character set using
the charset argument.
Returns a dictionary containing the OK packet information.
Instructs the server to write debugging information to the error
log. The connected user must have the
SUPER privilege.
Returns a dictionary containing the OK packet information.
This method makes specified database the default (current) database. In subsequent queries, this database is the default for table references that include no explicit database qualifier.
Returns a dictionary containing the OK packet information.
Checks whether the connection to the server is working.
This method is not to be used directly. Use ping() or is_connected() instead.
Returns a dictionary containing the OK packet information.
This method raises the NotSupportedError exception. Instead, use
the SHOW PROCESSLIST statement or query the
tables found in the database
INFORMATION_SCHEMA.
Asks the server to kill the thread specified by
mysql_pid. Although still available, it is
better to use the KILL SQL statement.
Returns a dictionary containing the OK packet information.
The following two lines have the same effect:
>>> cnx.cmd_process_kill(123)
>>> cnx.cmd_query('KILL 123')
This method sends a QUIT command to the MySQL
server, closing the current connection. Since there is no
response from the MySQL server, the packet that was sent is
returned.
This method sends the given statement to the
MySQL server and returns a result. To send multiple statements,
use the
cmd_query_iter()
method instead.
The returned dictionary contains information depending on what
kind of query was executed. If the query is a
SELECT statement, the result
contains information about columns. Other statements return a
dictionary containing OK or EOF packet information.
Errors received from the MySQL server are raised as exceptions.
An InterfaceError is raised when multiple
results are found.
Returns a dictionary.
Similar to the
cmd_query()
method, but returns a generator object to iterate through
results. Use cmd_query_iter() when sending
multiple statements, and separate the statements with
semicolons.
The following example shows how to iterate through the results after sending multiple statements:
statement = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cnx.cmd_query(statement, iterate=True):
if 'columns' in result:
columns = result['columns']
rows = cnx.get_rows()
else:
# do something useful with INSERT resultReturns a generator object.
This method flushes tables or caches, or resets replication
server information. The connected user must have the
RELOAD privilege.
The options argument should be a bitmask
value constructed using constants from the
constants.RefreshOption class.
For a list of options, see
Section 22.6.7.9, “Class constants.RefreshOption”.
Example:
>>> from mysql.connector import RefreshOption >>> refresh = RefreshOption.LOG | RefreshOption.THREADS >>> cnx.cmd_refresh(refresh)
Asks the database server to shut down. The connected user must
have the SHUTDOWN privilege.
Returns a dictionary containing the OK packet information.
Returns a dictionary containing information about the MySQL server including uptime in seconds and the number of running threads, questions, reloads, and open tables.
This method tries to send a QUIT command and
close the socket. It raises no exceptions.
MySQLConnection.close() is a synonymous
method name and more commonly used.
This method retrieves all or remaining rows of a query result
set, returning a tuple containing the rows as sequences and the
EOF packet information. The count argument can be used to obtain
a given number of rows. If count is not specified or is
None, all rows are retrieved.
The tuple returned by get_rows() consists of:
A list of tuples containing the row data as byte objects, or an empty list when no rows are available.
EOF packet information as a dictionary containing
status_flag and
warning_count.
An InterfaceError is raised when all rows
have been retrieved.
MySQLCursor
uses the get_rows() method to fetch rows.
Returns a tuple.
This method retrieves the next row of a query result set, returning a tuple.
The tuple returned by get_row() consists of:
The row as a tuple containing byte objects, or
None when no more rows are available.
EOF packet information as a dictionary containing
status_flag and
warning_count, or None
when the row returned is not the last row.
The get_row() method is used by
MySQLCursor
to fetch rows.
This method returns the MySQL server information verbatim as a
string, for example '5.6.11-log', or
None when not connected.
This method returns the MySQL server version as a tuple, or
None when not connected.
Reports whether the connection to MySQL Server is available.
This method checks whether the connection to MySQL is available
using the
ping()
method, but unlike ping(),
is_connected() returns
True when the connection is available,
False otherwise.
This method returns True if the client flag
was set, False otherwise.
Check whether the connection to the MySQL server is still available.
When reconnect is set to
True, one or more attempts are made to try to
reconnect to the MySQL server using the
reconnect() method. Use the
delay argument (seconds) if you want to wait
between each retry.
When the connection is not available, an
InterfaceError is raised. Use the
is_connected()
method to check the connection without raising an error.
Raises InterfaceError on errors.
Attempt to reconnect with the MySQL server.
The argument attempts specifies the number of
times a reconnect is tried. The delay
argument is the number of seconds to wait between each retry.
You might set the number of attempts higher and use a longer delay when you expect the MySQL server to be down for maintenance, or when you expect the network to be temporarily unavailable.
This method sends a ROLLBACK statement to the
MySQL server, undoing all data changes from the current
transaction. By default, Connector/Python does not autocommit,
so it is possible to cancel transactions when using
transactional storage engines such as InnoDB.
>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)", ('Jane'))
>>> cnx.rollback()
This method sets the character set and collation to be used for
the current connection. The charset argument
can be either the name of a character set, or the numerical
equivalent as defined in
constants.CharacterSet.
When collation is None,
the default collation for the character set is used.
In the following example, we set the character set to
latin1 and the collation to
latin1_swedish_ci (the default collation for:
latin1):
>>> cnx = mysql.connector.connect(user='scott')
>>> cnx.set_charset('latin1')
Specify a given collation as follows:
>>> cnx = mysql.connector.connect(user='scott')
>>> cnx.set_charset('latin1', 'latin1_general_ci')
This method sets the client flags which are used when connecting
with the MySQL server and returns the new value. The
flags argument can be either an integer or a
sequence of valid client flag values (see
Section 22.6.7.5, “Class constants.ClientFlag”).
If flags is a sequence, each item in the
sequence sets the flag when the value is positive or unset it
when negative. For example, to unset
LONG_FLAG and set the
FOUND_ROWS flags:
>>> from mysql.connector.constants import ClientFlag >>> cnx.set_client_flags([ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG]) >>> cnx.reconnect()
Note that client flags are only set or used when connecting with the MySQL server. It is therefore necessary to reconnect after making changes.
Returns an integer.
This property is used to toggle the autocommit feature of MySQL
and retrieve the current state. When the value evaluates to
True, autocommit is turned on, otherwise it
is turned off.
Note that autocommit is disabled by default when connecting
through Connector/Python. This can be toggled using the
connection
parameter autocommit.
When the autocommit is turned off, you must commit transactions when using transactional storage engines such as InnoDB or NDBCluster.
>>> cnx.autocommit False >>> cnx.autocommit = True >>> cnx.autocommit True
Returns True or False.
This property returns which character set is used for the connection, whether or not it is connected.
Returns a string.
This property returns which collation is used for the connection, whether or not it is connected.
Returns a string.
This property returns the integer connection ID (thread ID or
session ID) for the current connection or
None when not connected.
This property is used to set the current (active) database by
executing a USE statement. The property can
also be used to retrieve the current database name.
>>> cnx.database = 'test' >>> cnx.database = 'mysql' >>> cnx.database u'mysql'
Returns a string.
This property is used to toggle whether warnings should be
fetched automatically. It accepts True or
False (default).
Fetching warnings automatically could be useful when debugging queries. Cursors make warnings available through the method MySQLCursor.fetchwarnings().
>>> cnx.get_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
[(1.0,)]
>>> cursor.fetchwarnings()
[(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]
Returns True or False.
This property is used to toggle whether warnings should raise
exceptions. It accepts True or
False (default).
Toggling raise_on_warnings also toggles
get_warnings since warnings need to be
fetched so they can be raised as exceptions.
Note that you might always want to check setting SQL Mode if you would like to have the MySQL server directly report warnings as errors. It is also good to use transactional engines so transactions can be rolled back when catching the exception.
Result sets needs to be fetched completely before any exception can be raised. The following example shows the execution of a query which produces a warning
>>> cnx.raise_on_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
..
mysql.connector.errors.DataError: 1292: Truncated incorrect DOUBLE value: 'a'
Returns True or False.
This read-only property returns the host name or IP address used for connecting with the MySQL server.
Returns a string.
This read-only property returns the TCP/IP port used for connecting with the MySQL server.
Returns an integer.
This property is used to retrieve and set the SQL Modes for the current. The value should be list of different modes separated by comma (","), or a sequence of modes, preferably using the constants.SQLMode class.
To unset all modes, pass an empty string or an empty sequence.
>>> cnx.sql_mode = 'TRADITIONAL,NO_ENGINE_SUBSTITUTION'
>>> cnx.sql_mode.split(',')
[u'STRICT_TRANS_TABLES', u'STRICT_ALL_TABLES', u'NO_ZERO_IN_DATE',
u'NO_ZERO_DATE', u'ERROR_FOR_DIVISION_BY_ZERO', u'TRADITIONAL',
u'NO_AUTO_CREATE_USER', u'NO_ENGINE_SUBSTITUTION']
>>> from mysql.connector.constants import SQLMode
>>> cnx.sql_mode = [ SQLMode.NO_ZERO_DATE, SQLMode.REAL_AS_FLOAT]
>>> cnx.sql_mode
u'REAL_AS_FLOAT,NO_ZERO_DATE'Returns a string.
This property is used to set the time zone session variable for the current connection and retrieve it.
>>> cnx.time_zone = '+00:00'
>>> cur.execute('SELECT NOW()') ; cur.fetchone()
(datetime.datetime(2012, 6, 15, 11, 24, 36),)
>>> cnx.time_zone = '-09:00'
>>> cur.execute('SELECT NOW()') ; cur.fetchone()
(datetime.datetime(2012, 6, 15, 2, 24, 44),)
>>> cnx.time_zone
u'-09:00'
Returns a string.
This read-only property returns the Unix socket user for connecting with the MySQL server.
Returns a string.

User Comments
Add your own comment.