connector Package

connector Package

MySQL Connector/Python - MySQL drive written in Python

class mysql.connector.MySQL(*args, **kwargs)

Bases: mysql.connector.mysql.MySQLBase

Class implementing Python DB API v2.0.

close()
commit()

Shortcut for executing COMMIT.

connect(dsn='', user='', password='', host='127.0.0.1', port=3306, db=None, database=None, use_unicode=True, charset='utf8', get_warnings=False, raise_on_warnings=False, autocommit=False, unix_socket=None, connection_timeout=None, client_flags=0, buffered=False)
Establishes a connection to the MySQL Server. Called also when instansiating

a new MySQLConnection object through the __init__ method.

Possible parameters are:

dsn
(not used)
user
The username used to authenticate with the MySQL Server.
password
The password to authenticate the user with the MySQL Server.
host
The hostname or the IP address of the MySQL Server we are connecting with. (default 127.0.0.1)
port
TCP port to use for connecting to the MySQL Server. (default 3306)

database db

Initial database to use once we are connected with the MySQL Server. The db argument is synonym, but database takes precedence.
use_unicode
If set to true, string values received from MySQL will be returned as Unicode strings. Default: True
charset
Which character shall we use for sending data to MySQL. One can still override this by using the SET NAMES command directly, but this is discouraged. Instead, use the set_charset() method if you want to change it. Default: Whatever the MySQL server has default.
get_warnings
If set to true, whenever a query gives a warning, a SHOW WARNINGS will be done to fetch them. They will be available as MySQLCursor.warnings. The default is to ignore these warnings, for debugging it’s good to enable it though, or use strict mode in MySQL to make most of these warnings errors. Default: False
raise_on_warnings
If set to True, warnings will be raised as exceptions. raise_on_warings overrides get_warnings. Default: False
autocommit
Auto commit is OFF by default, which is required by the Python Db API 2.0 specification. Default: False
unix_socket
Full path to the MySQL Server UNIX socket. By default TCP connection will be used using the address specified by the host argument.
connection_timeout
Timeout for the TCP and UNIX socket connection.
client_flags
Allows to set flags for the connection. Check following for possible flags:
>>> from mysql.connector.constants import ClientFlag
>>> print '

‘.join(ClientFlag.get_full_info())

buffered
When set to True .execute() will fetch the rows immediatly.
cursor()
remove_cursor(c)
rollback()

Shortcut for executing ROLLBACK

mysql.connector.Connect(*args, **kwargs)

Shortcut for creating a mysql.MySQL object.

class mysql.connector.FieldType

Bases: mysql.connector.constants._constants

BIT = 16
BLOB = 252
DATE = 10
DATETIME = 12
DECIMAL = 0
DOUBLE = 5
ENUM = 247
FLOAT = 4
GEOMETRY = 255
INT24 = 9
LONG = 3
LONGLONG = 8
LONG_BLOB = 251
MEDIUM_BLOB = 250
NEWDATE = 14
NEWDECIMAL = 246
NULL = 6
SET = 248
SHORT = 2
STRING = 254
TIME = 11
TIMESTAMP = 7
TINY = 1
TINY_BLOB = 249
VARCHAR = 15
VAR_STRING = 253
YEAR = 13
desc = {'LONGLONG': (8, 'LONGLONG'), 'SHORT': (2, 'SHORT'), 'LONG': (3, 'LONG'), 'DATE': (10, 'DATE'), 'NEWDATE': (14, 'NEWDATE'), 'NULL': (6, 'NULL'), 'TIMESTAMP': (7, 'TIMESTAMP'), 'SET': (248, 'SET'), 'VARCHAR': (15, 'VARCHAR'), 'TINY': (1, 'TINY'), 'NEWDECIMAL': (246, 'NEWDECIMAL'), 'BIT': (16, 'BIT'), 'MEDIUM_BLOB': (250, 'MEDIUM_BLOB'), 'VAR_STRING': (253, 'VAR_STRING'), 'STRING': (254, 'STRING'), 'DECIMAL': (0, 'DECIMAL'), 'ENUM': (247, 'ENUM'), 'TINY_BLOB': (249, 'TINY_BLOB'), 'DATETIME': (12, 'DATETIME'), 'YEAR': (13, 'YEAR'), 'INT24': (9, 'INT24'), 'DOUBLE': (5, 'DOUBLE'), 'FLOAT': (4, 'FLOAT'), 'GEOMETRY': (255, 'GEOMETRY'), 'BLOB': (252, 'BLOB'), 'TIME': (11, 'TIME'), 'LONG_BLOB': (251, 'LONG_BLOB')}
classmethod get_binary_types()
classmethod get_number_types()
classmethod get_string_types()
classmethod get_timestamp_types()
prefix = 'FIELD_TYPE_'
class mysql.connector.FieldFlag

Bases: mysql.connector.constants._constantflags

Field flags as found in MySQL sources mysql-src/include/mysql_com.h

AUTO_INCREMENT = 512
BINARY = 128
BINCMP = 131072
BLOB = 16
ENUM = 256
FIELD_IN_ADD_INDEX = 1048576
FIELD_IN_PART_FUNC = 524288
FIELD_IS_RENAMED = 2097152
GET_FIXED_FIELDS = 262144
GROUP = 16384
MULTIPLE_KEY = 8
NOT_NULL = 1
NO_DEFAULT_VALUE = 4096
NUM = 16384
ON_UPDATE_NOW = 8192
PART_KEY = 32768
PRI_KEY = 2
SET = 2048
TIMESTAMP = 1024
UNIQUE = 65536
UNIQUE_KEY = 4
UNSIGNED = 32
ZEROFILL = 64
desc = {'GROUP': (16384, 'Intern: Group field'), 'FIELD_IN_PART_FUNC': (524288, 'Field part of partition func'), 'PRI_KEY': (2, 'Field is part of a primary key'), 'NO_DEFAULT_VALUE': (4096, "Field doesn't have default value"), 'PART_KEY': (32768, 'Intern; Part of some key'), 'NOT_NULL': (1, "Field can't be NULL"), 'MULTIPLE_KEY': (8, 'Field is part of a key'), 'SET': (2048, 'field is a set'), 'UNIQUE_KEY': (4, 'Field is part of a unique key'), 'AUTO_INCREMENT': (512, 'field is a autoincrement field'), 'UNSIGNED': (32, 'Field is unsigned'), 'GET_FIXED_FIELDS': (262144, 'Used to get fields in item tree'), 'NUM': (16384, 'Field is num (for clients)'), 'FIELD_IN_ADD_INDEX': (1048576, 'Intern: Field used in ADD INDEX'), 'ZEROFILL': (64, 'Field is zerofill'), 'ON_UPDATE_NOW': (8192, 'Field is set to NOW on UPDATE'), 'ENUM': (256, 'field is an enum'), 'BINCMP': (131072, 'Intern: Used by sql_yacc'), 'FIELD_IS_RENAMED': (2097152, 'Intern: Field is being renamed'), 'UNIQUE': (65536, 'Intern: Used by sql_yacc'), 'BINARY': (128, 'Field is binary '), 'TIMESTAMP': (1024, 'Field is a timestamp'), 'BLOB': (16, 'Field is a blob')}
class mysql.connector.ClientFlag

Bases: mysql.connector.constants._constantflags

Client Options as found in the MySQL sources mysql-src/include/mysql_com.h

COMPRESS = 32
CONNECT_WITH_DB = 8
FOUND_ROWS = 2
IGNORE_SIGPIPE = 4096
IGNORE_SPACE = 256
INTERACTIVE = 1024
LOCAL_FILES = 128
LONG_FLAG = 4
LONG_PASSWD = 1
MULTI_RESULTS = 131072
MULTI_STATEMENTS = 65536
NO_SCHEMA = 16
ODBC = 64
PROTOCOL_41 = 512
REMEMBER_OPTIONS = 2147483648
RESERVED = 16384
SECURE_CONNECTION = 32768
SSL = 2048
SSL_VERIFY_SERVER_CERT = 1073741824
TRANSACTIONS = 8192
default = [1, 4, 8, 512, 8192, 32768, 65536, 131072]
desc = {'NO_SCHEMA': (16, "Don't allow database.table.column"), 'IGNORE_SIGPIPE': (4096, 'IGNORE sigpipes'), 'SECURE_CONNECTION': (32768, 'New 4.1 authentication'), 'RESERVED': (16384, 'Old flag for 4.1 protocol'), 'FOUND_ROWS': (2, 'Found instead of affected rows'), 'TRANSACTIONS': (8192, 'Client knows about transactions'), 'ODBC': (64, 'ODBC client'), 'SSL_VERIFY_SERVER_CERT': (1073741824, ''), 'COMPRESS': (32, 'Can use compression protocol'), 'CONNECT_WITH_DB': (8, 'One can specify db on connect'), 'REMEMBER_OPTIONS': (2147483648, ''), 'SSL': (2048, 'Switch to SSL after handshake'), 'LOCAL_FILES': (128, 'Can use LOAD DATA LOCAL'), 'PROTOCOL_41': (512, 'New 4.1 protocol'), 'LONG_FLAG': (4, 'Get all column flags'), 'MULTI_RESULTS': (131072, 'Enable/disable multi-results'), 'MULTI_STATEMENTS': (65536, 'Enable/disable multi-stmt support'), 'LONG_PASSWD': (1, 'New more secure passwords'), 'IGNORE_SPACE': (256, "Ignore spaces before ''"), 'INTERACTIVE': (1024, 'This is an interactive client')}
classmethod get_default()
class mysql.connector.CharacterSet

Bases: mysql.connector.constants._constants

List of supported character sets with their collations. This maps to the character set we get from the server within the handshake packet.

To update this list, use the following query:
SELECT ID,CHARACTER_SET_NAME, COLLATION_NAME
FROM INFORMATION_SCHEMA.COLLATIONS ORDER BY ID

This list is hardcoded because we want to avoid doing each time the above query to get the name of the character set used.

classmethod get_charset_info(name, collation=None)

Returns information about the charset and optional collation.

classmethod get_desc(setid)

Returns info string about the charset for given MySQL ID.

classmethod get_info(setid)

Returns information about the charset for given MySQL ID.

classmethod get_supported()

Returns a list with names of all supproted character sets.

class mysql.connector.RefreshOption

Bases: mysql.connector.constants._constants

Options used when sending the COM_REFRESH server command.

GRANT = 1
HOST = 8
LOG = 2
SLAVE = 64
STATUS = 16
TABLES = 4
THREADS = 32
desc = {'STATUS': (16, 'Flush status variables'), 'TABLES': (4, 'close all tables'), 'SLAVE': (64, 'Reset master info and restart slave thread'), 'LOG': (2, 'Start on new log file'), 'GRANT': (1, 'Refresh grant tables'), 'THREADS': (32, 'Flush thread cache'), 'HOSTS': (8, 'Flush host cache')}
exception mysql.connector.Error(m, errno=None, values=None)

Bases: exceptions.StandardError

exception mysql.connector.Warning

Bases: exceptions.StandardError

exception mysql.connector.InterfaceError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.Error

exception mysql.connector.DatabaseError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.Error

exception mysql.connector.NotSupportedError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.DataError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.IntegrityError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.ProgrammingError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.OperationalError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.InternalError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

mysql.connector.connect(*args, **kwargs)

Shortcut for creating a mysql.MySQL object.

mysql.connector.Date

alias of date

mysql.connector.Time

alias of time

mysql.connector.Timestamp

alias of datetime

mysql.connector.Binary

alias of str

mysql.connector.DateFromTicks(ticks)
mysql.connector.DateFromTicks(ticks)
mysql.connector.TimestampFromTicks(ticks)

_version Module

Holds version of MySQL Connector/Python

connection Module

Implementing communication to MySQL servers

class mysql.connector.connection.MySQLBaseConnection(prtcls=None)

Bases: object

Base class for MySQL Connections subclasses.

Should not be used directly but overloaded, changing the open_connection part. Examples over subclasses are

MySQLTCPConnection MySQLUNIXConnection
close_connection()
do_handshake()
get_address()
open_connection()
recv()

Receive packets using the socket from the server.

send(buf)

Send packets using the socket to the server.

set_connection_timeout(timeout)
set_protocol(prtcls)
class mysql.connector.connection.MySQLTCPConnection(prtcls=None, host='127.0.0.1', port=3306)

Bases: mysql.connector.connection.MySQLBaseConnection

Opens a TCP connection to the MySQL Server.

get_address()
open_connection()

Opens a TCP Connection and checks the MySQL handshake.

class mysql.connector.connection.MySQLUnixConnection(prtcls=None, unix_socket='/tmp/mysql.sock')

Bases: mysql.connector.connection.MySQLBaseConnection

Opens a connection through the UNIX socket of the MySQL Server.

get_address()
open_connection()

Opens a UNIX socket and checks the MySQL handshake.

constants Module

Various MySQL constants and character sets

class mysql.connector.constants.CharacterSet

Bases: mysql.connector.constants._constants

List of supported character sets with their collations. This maps to the character set we get from the server within the handshake packet.

To update this list, use the following query:
SELECT ID,CHARACTER_SET_NAME, COLLATION_NAME
FROM INFORMATION_SCHEMA.COLLATIONS ORDER BY ID

This list is hardcoded because we want to avoid doing each time the above query to get the name of the character set used.

classmethod get_charset_info(name, collation=None)

Returns information about the charset and optional collation.

classmethod get_desc(setid)

Returns info string about the charset for given MySQL ID.

classmethod get_info(setid)

Returns information about the charset for given MySQL ID.

classmethod get_supported()

Returns a list with names of all supproted character sets.

class mysql.connector.constants.ClientFlag

Bases: mysql.connector.constants._constantflags

Client Options as found in the MySQL sources mysql-src/include/mysql_com.h

COMPRESS = 32
CONNECT_WITH_DB = 8
FOUND_ROWS = 2
IGNORE_SIGPIPE = 4096
IGNORE_SPACE = 256
INTERACTIVE = 1024
LOCAL_FILES = 128
LONG_FLAG = 4
LONG_PASSWD = 1
MULTI_RESULTS = 131072
MULTI_STATEMENTS = 65536
NO_SCHEMA = 16
ODBC = 64
PROTOCOL_41 = 512
REMEMBER_OPTIONS = 2147483648
RESERVED = 16384
SECURE_CONNECTION = 32768
SSL = 2048
SSL_VERIFY_SERVER_CERT = 1073741824
TRANSACTIONS = 8192
default = [1, 4, 8, 512, 8192, 32768, 65536, 131072]
desc = {'NO_SCHEMA': (16, "Don't allow database.table.column"), 'IGNORE_SIGPIPE': (4096, 'IGNORE sigpipes'), 'SECURE_CONNECTION': (32768, 'New 4.1 authentication'), 'RESERVED': (16384, 'Old flag for 4.1 protocol'), 'FOUND_ROWS': (2, 'Found instead of affected rows'), 'TRANSACTIONS': (8192, 'Client knows about transactions'), 'ODBC': (64, 'ODBC client'), 'SSL_VERIFY_SERVER_CERT': (1073741824, ''), 'COMPRESS': (32, 'Can use compression protocol'), 'CONNECT_WITH_DB': (8, 'One can specify db on connect'), 'REMEMBER_OPTIONS': (2147483648, ''), 'SSL': (2048, 'Switch to SSL after handshake'), 'LOCAL_FILES': (128, 'Can use LOAD DATA LOCAL'), 'PROTOCOL_41': (512, 'New 4.1 protocol'), 'LONG_FLAG': (4, 'Get all column flags'), 'MULTI_RESULTS': (131072, 'Enable/disable multi-results'), 'MULTI_STATEMENTS': (65536, 'Enable/disable multi-stmt support'), 'LONG_PASSWD': (1, 'New more secure passwords'), 'IGNORE_SPACE': (256, "Ignore spaces before ''"), 'INTERACTIVE': (1024, 'This is an interactive client')}
classmethod get_default()
class mysql.connector.constants.FieldFlag

Bases: mysql.connector.constants._constantflags

Field flags as found in MySQL sources mysql-src/include/mysql_com.h

AUTO_INCREMENT = 512
BINARY = 128
BINCMP = 131072
BLOB = 16
ENUM = 256
FIELD_IN_ADD_INDEX = 1048576
FIELD_IN_PART_FUNC = 524288
FIELD_IS_RENAMED = 2097152
GET_FIXED_FIELDS = 262144
GROUP = 16384
MULTIPLE_KEY = 8
NOT_NULL = 1
NO_DEFAULT_VALUE = 4096
NUM = 16384
ON_UPDATE_NOW = 8192
PART_KEY = 32768
PRI_KEY = 2
SET = 2048
TIMESTAMP = 1024
UNIQUE = 65536
UNIQUE_KEY = 4
UNSIGNED = 32
ZEROFILL = 64
desc = {'GROUP': (16384, 'Intern: Group field'), 'FIELD_IN_PART_FUNC': (524288, 'Field part of partition func'), 'PRI_KEY': (2, 'Field is part of a primary key'), 'NO_DEFAULT_VALUE': (4096, "Field doesn't have default value"), 'PART_KEY': (32768, 'Intern; Part of some key'), 'NOT_NULL': (1, "Field can't be NULL"), 'MULTIPLE_KEY': (8, 'Field is part of a key'), 'SET': (2048, 'field is a set'), 'UNIQUE_KEY': (4, 'Field is part of a unique key'), 'AUTO_INCREMENT': (512, 'field is a autoincrement field'), 'UNSIGNED': (32, 'Field is unsigned'), 'GET_FIXED_FIELDS': (262144, 'Used to get fields in item tree'), 'NUM': (16384, 'Field is num (for clients)'), 'FIELD_IN_ADD_INDEX': (1048576, 'Intern: Field used in ADD INDEX'), 'ZEROFILL': (64, 'Field is zerofill'), 'ON_UPDATE_NOW': (8192, 'Field is set to NOW on UPDATE'), 'ENUM': (256, 'field is an enum'), 'BINCMP': (131072, 'Intern: Used by sql_yacc'), 'FIELD_IS_RENAMED': (2097152, 'Intern: Field is being renamed'), 'UNIQUE': (65536, 'Intern: Used by sql_yacc'), 'BINARY': (128, 'Field is binary '), 'TIMESTAMP': (1024, 'Field is a timestamp'), 'BLOB': (16, 'Field is a blob')}
class mysql.connector.constants.FieldType

Bases: mysql.connector.constants._constants

BIT = 16
BLOB = 252
DATE = 10
DATETIME = 12
DECIMAL = 0
DOUBLE = 5
ENUM = 247
FLOAT = 4
GEOMETRY = 255
INT24 = 9
LONG = 3
LONGLONG = 8
LONG_BLOB = 251
MEDIUM_BLOB = 250
NEWDATE = 14
NEWDECIMAL = 246
NULL = 6
SET = 248
SHORT = 2
STRING = 254
TIME = 11
TIMESTAMP = 7
TINY = 1
TINY_BLOB = 249
VARCHAR = 15
VAR_STRING = 253
YEAR = 13
desc = {'LONGLONG': (8, 'LONGLONG'), 'SHORT': (2, 'SHORT'), 'LONG': (3, 'LONG'), 'DATE': (10, 'DATE'), 'NEWDATE': (14, 'NEWDATE'), 'NULL': (6, 'NULL'), 'TIMESTAMP': (7, 'TIMESTAMP'), 'SET': (248, 'SET'), 'VARCHAR': (15, 'VARCHAR'), 'TINY': (1, 'TINY'), 'NEWDECIMAL': (246, 'NEWDECIMAL'), 'BIT': (16, 'BIT'), 'MEDIUM_BLOB': (250, 'MEDIUM_BLOB'), 'VAR_STRING': (253, 'VAR_STRING'), 'STRING': (254, 'STRING'), 'DECIMAL': (0, 'DECIMAL'), 'ENUM': (247, 'ENUM'), 'TINY_BLOB': (249, 'TINY_BLOB'), 'DATETIME': (12, 'DATETIME'), 'YEAR': (13, 'YEAR'), 'INT24': (9, 'INT24'), 'DOUBLE': (5, 'DOUBLE'), 'FLOAT': (4, 'FLOAT'), 'GEOMETRY': (255, 'GEOMETRY'), 'BLOB': (252, 'BLOB'), 'TIME': (11, 'TIME'), 'LONG_BLOB': (251, 'LONG_BLOB')}
classmethod get_binary_types()
classmethod get_number_types()
classmethod get_string_types()
classmethod get_timestamp_types()
prefix = 'FIELD_TYPE_'
class mysql.connector.constants.RefreshOption

Bases: mysql.connector.constants._constants

Options used when sending the COM_REFRESH server command.

GRANT = 1
HOST = 8
LOG = 2
SLAVE = 64
STATUS = 16
TABLES = 4
THREADS = 32
desc = {'STATUS': (16, 'Flush status variables'), 'TABLES': (4, 'close all tables'), 'SLAVE': (64, 'Reset master info and restart slave thread'), 'LOG': (2, 'Start on new log file'), 'GRANT': (1, 'Refresh grant tables'), 'THREADS': (32, 'Flush thread cache'), 'HOSTS': (8, 'Flush host cache')}
class mysql.connector.constants.ServerCmd

Bases: mysql.connector.constants._constants

BINLOG_DUMP = 18
CHANGE_USER = 17
CONNECT = 11
CONNECT_OUT = 20
CREATE_DB = 5
DAEMON = 29
DEBUG = 13
DELAYED_INSERT = 16
DROP_DB = 6
FIELD_LIST = 4
INIT_DB = 2
PING = 14
PROCESS_INFO = 10
PROCESS_KILL = 12
QUERY = 3
QUIT = 1
REFRESH = 7
REGISTER_SLAVE = 21
SET_OPTION = 27
SHUTDOWN = 8
SLEEP = 0
STATISTICS = 9
STMT_CLOSE = 25
STMT_EXECUTE = 23
STMT_FETCH = 28
STMT_PREPARE = 22
STMT_RESET = 26
STMT_SEND_LONG_DATA = 24
TABLE_DUMP = 19
TIME = 15
class mysql.connector.constants.ServerFlag

Bases: mysql.connector.constants._constantflags

Server flags as found in the MySQL sources mysql-src/include/mysql_com.h

MORE_RESULTS_EXISTS = 8
QUERY_NO_GOOD_INDEX_USED = 16
QUERY_NO_INDEX_USED = 32
STATUS_AUTOCOMMIT = 2
STATUS_CURSOR_EXISTS = 64
STATUS_DB_DROPPED = 256
STATUS_IN_TRANS = 1
STATUS_LAST_ROW_SENT = 128
STATUS_NO_BACKSLASH_ESCAPES = 512
desc = {'SERVER_STATUS_DB_DROPPED': (256, 'A database was dropped'), 'SERVER_MORE_RESULTS_EXISTS': (8, 'Multi query - next query exists'), 'SERVER_STATUS_NO_BACKSLASH_ESCAPES': (512, ''), 'SERVER_STATUS_CURSOR_EXISTS': (64, ''), 'SERVER_STATUS_AUTOCOMMIT': (2, 'Server in auto_commit mode'), 'SERVER_STATUS_LAST_ROW_SENT': (128, ''), 'SERVER_QUERY_NO_INDEX_USED': (32, ''), 'SERVER_STATUS_IN_TRANS': (1, 'Transaction has started'), 'SERVER_QUERY_NO_GOOD_INDEX_USED': (16, '')}

conversion Module

Converting MySQL and Python types

class mysql.connector.conversion.ConverterBase(charset='utf8', use_unicode=True)

Bases: object

escape(buf)
quote(buf)
set_charset(charset)
set_unicode(value=True)
to_mysql(value)
to_python(vtype, value)
class mysql.connector.conversion.MySQLConverter(charset=None, use_unicode=True)

Bases: mysql.connector.conversion.ConverterBase

A converted class grouping:

o escape method: for escpaing values send to MySQL o quoting method: for quoting values send to MySQL in statements o conversion mapping: maps Python and MySQL data types to

function for converting them.

This class should be overloaded whenever one needs differences in how values are to be converted. Each MySQLConnection object has a default_converter property, which can be set like

MySQL.converter(CustomMySQLConverter)
escape(value)

Escapes special characters as they are expected to by when MySQL receives them. As found in MySQL source mysys/charset.c

Returns the value if not a string, or the escaped string.

quote(buf)
Quote the parameters for commands. General rules:
o numbers are returns as str type (because operation expect it) o None is returned as str(‘NULL’) o String are quoted with single quotes ‘<string>’

Returns a string.

to_mysql(value)
to_python(flddsc, value)

Converts a given value coming from MySQL to a certain type in Python. The flddsc contains additional information for the field in the table. It’s an element from MySQLCursor.description.

Returns a mixed value.

cursor Module

Cursor classes

class mysql.connector.cursor.CursorBase

Bases: object

Base for defining MySQLCursor. This class is a skeleton and defines methods and members as required for the Python Database API Specification v2.0.

It’s better to inherite from MySQLCursor.

callproc(procname, args=())
close()
execute(operation, params=())
executemany(operation, seqparams)
fetchall()
fetchmany(size=1)
fetchone()
nextset()
reset()
setinputsizes(sizes)
setoutputsize(size, column=None)
class mysql.connector.cursor.MySQLCursor(db=None)

Bases: mysql.connector.cursor.CursorBase

Default cursor which fetches all rows and stores it for later usage. It uses the converter set for the MySQLConnection to map MySQL types to Python types automatically.

This class should be inherited whenever other functionallity is required. An example would to change the fetch* member functions to return dictionaries instead of lists of values.

Implements the Python Database API Specification v2.0.

Possible parameters are:

db
A MySQLConnection instance.
callproc(procname, args=())

Calls a stored procedue with the given arguments

The arguments will be set during this session, meaning they will be called like _<procname>__arg<nr> where <nr> is an enumeration (+1) of the arguments.

Coding Example:

1) Definining the Stored Routine in MySQL: CREATE PROCEDURE multiply(IN pFac1 INT, IN pFac2 INT, OUT pProd INT) BEGIN

SET pProd := pFac1 * pFac2;

END

2) Executing in Python: args = (5,5,0) # 0 is to hold pprod cursor.callproc(multiply, args) print cursor.fetchone()

The last print should output (‘5’, ‘5’, 25L)

Does not return a value, but a result set will be available when the CALL-statement execute succesfully. Raises exceptions when something is wrong.

close()

Close the cursor, disconnecting it from the MySQL object.

Returns True when succesful, otherwise False.

execute(operation, params=None)

Executes the given operation. The parameters given through params are used to substitute %%s in the operation string. For example, getting all rows where id is 5:

cursor.execute(“SELECT * FROM t1 WHERE id = %s”, (5,))

If warnings where generated, and db.get_warnings is True, then self._warnings will be a list containing these warnings.

Raises exceptions when any error happens.

executemany(operation, seq_params)

Loops over seq_params and calls excute()

fetchall()
fetchmany(size=None)
fetchone()
fetchwarnings()
getlastrowid()
next()

Used for iterating over the result set. Calles self.fetchone() to get the next row.

set_connection(db)
class mysql.connector.cursor.MySQLCursorBuffered(db=None)

Bases: mysql.connector.cursor.MySQLCursor

Cursor which fetches rows within execute()

fetchall()
fetchmany(size=None)
reset()

dbapi Module

DB API v2.0 required

mysql.connector.dbapi.DateFromTicks(ticks)
mysql.connector.dbapi.TimeFromTicks(ticks)
mysql.connector.dbapi.TimestampFromTicks(ticks)

errors Module

Python exceptions

class mysql.connector.errors.ClientError

Bases: object

client_errors = {2048: 'Invalid connection handle', 2049: "Connection using old (pre-4.1.1) authentication protocol refused (client option 'secure_auth' enabled)", 2050: 'Row retrieval was canceled by mysql_stmt_close() call', 2051: 'Attempt to read column without prior row fetch', 2052: 'Prepared statement contains no metadata', 2053: 'Attempt to read a row while there is no result set associated with the statement', 2054: 'This feature is not implemented yet', 2055: "Lost connection to MySQL server at '%s', system error: %d", 2056: 'Statement closed indirectly because of a preceeding %s() call', 2057: 'The number of columns in the result set differs from the number of bound buffers. You must reset the statement, rebind the result set columns, and execute the statement again', 2000: 'Unknown MySQL error', 2001: "Can't create UNIX socket (%d)", 2002: "Can't connect to local MySQL server through socket '%s' (%s)", 2003: "Can't connect to MySQL server on '%s' (%s)", 2004: "Can't create TCP/IP socket (%s)", 2005: "Unknown MySQL server host '%s' (%s)", 2006: 'MySQL server has gone away', 2007: 'Protocol mismatch; server version = %d, client version = %d', 2008: 'MySQL client ran out of memory', 2009: 'Wrong host info', 2010: 'Localhost via UNIX socket', 2011: '%s via TCP/IP', 2012: 'Error in server handshake', 2013: 'Lost connection to MySQL server during query', 2014: "Commands out of sync; you can't run this command now", 2015: 'Named pipe: %s', 2016: "Can't wait for named pipe to host: %s pipe: %s (%d)", 2017: "Can't open named pipe to host: %s pipe: %s (%d)", 2018: "Can't set state of named pipe to host: %s pipe: %s (%d)", 2019: "Can't initialize character set %s (path: %s)", 2020: "Got packet bigger than 'max_allowed_packet' bytes", 2021: 'Embedded server', 2022: 'Error on SHOW SLAVE STATUS:', 2023: 'Error on SHOW SLAVE HOSTS:', 2024: 'Error connecting to slave:', 2025: 'Error connecting to master:', 2026: 'SSL connection error', 2027: 'Malformed packet', 2028: "This client library is licensed only for use with MySQL servers having '%s' license", 2029: 'Invalid use of null pointer', 2030: 'Statement not prepared', 2031: 'No data supplied for parameters in prepared statement', 2032: 'Data truncated', 2033: 'No parameters exist in the statement', 2034: 'Invalid parameter number', 2035: "Can't send long data for non-string/non-binary data types (parameter: %d)", 2036: 'Using unsupported buffer type: %d (parameter: %d)', 2037: 'Shared memory: %s', 2038: "Can't open shared memory; client could not create request event (%d)", 2039: "Can't open shared memory; no answer event received from server (%d)", 2040: "Can't open shared memory; server could not allocate file mapping (%d)", 2041: "Can't open shared memory; server could not get pointer to file mapping (%d)", 2042: "Can't open shared memory; client could not allocate file mapping (%d)", 2043: "Can't open shared memory; client could not get pointer to file mapping (%d)", 2044: "Can't open shared memory; client could not create %s event (%d)", 2045: "Can't open shared memory; no answer from server (%d)", 2046: "Can't open shared memory; cannot send request event to server (%d)", 2047: 'Wrong or unknown protocol'}
classmethod get_error_msg(errno, values=None)
exception mysql.connector.errors.DataError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.errors.DatabaseError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.Error

exception mysql.connector.errors.Error(m, errno=None, values=None)

Bases: exceptions.StandardError

exception mysql.connector.errors.IntegrityError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.errors.InterfaceError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.Error

exception mysql.connector.errors.InternalError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.errors.NotSupportedError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.errors.OperationalError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.errors.ProgrammingError(m=None, errno=None, values=None)

Bases: mysql.connector.errors.DatabaseError

exception mysql.connector.errors.Warning

Bases: exceptions.StandardError

mysql.connector.errors.get_mysql_exception(errno, msg)

mysql Module

Main classes for interacting with MySQL

class mysql.connector.mysql.MySQL(*args, **kwargs)

Bases: mysql.connector.mysql.MySQLBase

Class implementing Python DB API v2.0.

close()
commit()

Shortcut for executing COMMIT.

connect(dsn='', user='', password='', host='127.0.0.1', port=3306, db=None, database=None, use_unicode=True, charset='utf8', get_warnings=False, raise_on_warnings=False, autocommit=False, unix_socket=None, connection_timeout=None, client_flags=0, buffered=False)
Establishes a connection to the MySQL Server. Called also when instansiating

a new MySQLConnection object through the __init__ method.

Possible parameters are:

dsn
(not used)
user
The username used to authenticate with the MySQL Server.
password
The password to authenticate the user with the MySQL Server.
host
The hostname or the IP address of the MySQL Server we are connecting with. (default 127.0.0.1)
port
TCP port to use for connecting to the MySQL Server. (default 3306)

database db

Initial database to use once we are connected with the MySQL Server. The db argument is synonym, but database takes precedence.
use_unicode
If set to true, string values received from MySQL will be returned as Unicode strings. Default: True
charset
Which character shall we use for sending data to MySQL. One can still override this by using the SET NAMES command directly, but this is discouraged. Instead, use the set_charset() method if you want to change it. Default: Whatever the MySQL server has default.
get_warnings
If set to true, whenever a query gives a warning, a SHOW WARNINGS will be done to fetch them. They will be available as MySQLCursor.warnings. The default is to ignore these warnings, for debugging it’s good to enable it though, or use strict mode in MySQL to make most of these warnings errors. Default: False
raise_on_warnings
If set to True, warnings will be raised as exceptions. raise_on_warings overrides get_warnings. Default: False
autocommit
Auto commit is OFF by default, which is required by the Python Db API 2.0 specification. Default: False
unix_socket
Full path to the MySQL Server UNIX socket. By default TCP connection will be used using the address specified by the host argument.
connection_timeout
Timeout for the TCP and UNIX socket connection.
client_flags
Allows to set flags for the connection. Check following for possible flags:
>>> from mysql.connector.constants import ClientFlag
>>> print '

‘.join(ClientFlag.get_full_info())

buffered
When set to True .execute() will fetch the rows immediatly.
cursor()
remove_cursor(c)
rollback()

Shortcut for executing ROLLBACK

class mysql.connector.mysql.MySQLBase

Bases: object

MySQLBase

connect()

To be implemented while subclassing MySQLBase.

disconnect()

Disconnect from the MySQL server.

get_characterset_info()
get_server_info()

Returns the server version as a string

get_server_threadid()

Returns the MySQL threadid of the connection.

get_server_version()

Returns the server version as a tuple

is_connected()

Check whether we are connected to the MySQL server.

isset_client_flag(flag)
ping()

Check whether we are connected to the MySQL server.

set_autocommit(switch)

Set auto commit on or off. The argument ‘switch’ must be a boolean type.

set_buffered(val=False)

Sets whether cursor .execute() fetches rows

set_charset(name)

Set the character set used for the connection. This is the recommended way of change it per connection basis. It does execute SET NAMES internally, but it’s good not to use this command directly, since we are setting some other members accordingly.

set_charset_info(info=None, charset=None)
set_client_flag(flag)
set_client_flags(flags)
set_connection_timeout(timeout)
set_converter_class(convclass)

Set the converter class to be used. This should be a class overloading methods and members of conversion.MySQLConverter.

set_database(database)

Set the database to be used after connection succeeded.

set_host(host)

Set the host for connection to the MySQL server.

set_login(username=None, password=None)

Set the username and/or password for the user connecting to the MySQL Server.

set_port(port)

Set the TCP port to be used when connecting to the server, usually 3306.

set_unicode(value=True)

Set whether we return string fields as unicode or not. Default is True.

set_unixsocket(loc)

Set the UNIX Socket location. Does not check if it exists.

set_warnings(fetch=False, raise_on_warnings=False)

Set how to handle warnings coming from MySQL

Set wheter we should get warnings whenever an operation produced some. If you set raise_on_warnings to True, any warning will be raised as a DataError exception.

unset_client_flag(flag)

protocol Module

Implementing the MySQL Client/Server protocol

class mysql.connector.protocol.Auth(packet=None, client_flags=0, pktnr=0)

Bases: mysql.connector.protocol.PacketOut

create(username=None, password=None, database=None, seed=None, charset=33)
scramble(passwd, seed)
set_client_flags(flags)
set_login(username, password, database=None)
class mysql.connector.protocol.BasePacket

Bases: object

is_valid(buf=None)
class mysql.connector.protocol.ChangeUserPacket

Bases: mysql.connector.protocol.Auth

create(username=None, password=None, database=None, charset=8, seed=None)
class mysql.connector.protocol.CommandPacket(cmd=None, arg=None)

Bases: mysql.connector.protocol.PacketOut

create()
set_argument(arg)
set_command(cmd)
class mysql.connector.protocol.EOFPacket(buf=None)

Bases: mysql.connector.protocol.PacketIn

class mysql.connector.protocol.ErrorResultPacket(buf=None)

Bases: mysql.connector.protocol.PacketIn

class mysql.connector.protocol.FieldPacket(buf=None)

Bases: mysql.connector.protocol.PacketIn

get_description()

Returns a description as a list useful for cursors.

This function returns a list as defined in the Python Db API v2.0 specification.

class mysql.connector.protocol.Handshake(buf=None)

Bases: mysql.connector.protocol.PacketIn

get_dict()
class mysql.connector.protocol.KillPacket(arg)

Bases: mysql.connector.protocol.CommandPacket

create()
set_argument(arg)
class mysql.connector.protocol.MySQLProtocol(conn, handshake=None)

Bases: object

Class handling the MySQL Protocol.

MySQL v4.1 Client/Server Protocol is currently supported.

cmd_change_user(username, password, database=None)

Change the user with given username and password to another optional database.

cmd_debug()

Send DEBUG command to the MySQL Server

Needs SUPER privileges. The output will go to the MySQL server error log.

Returns True when it was succesful.

cmd_init_db(database)

Send command to server to change databases.

cmd_ping()

Ping the MySQL server to check if the connection is still alive.

Returns True when alive, False when server doesn’t respond.

cmd_process_info()

Gets the process list from the MySQL Server.

Returns a list of dictionaries which corresponds to the output of SHOW PROCESSLIST of MySQL. The data is converted to Python types.

cmd_process_kill(mypid)

Kills a MySQL process using it’s ID.

The mypid must be an integer.

cmd_query(query)

Sends a query to the server.

Returns a tuple, when the query returns a result. The tuple consist number of fields and a list containing their descriptions. If the query doesn’t return a result set, the an OKResultPacket will be returned.

cmd_quit()

Closes the current connection with the server.

cmd_refresh(opts)

Send the Refresh command to the MySQL server.

The argument should be a bitwise value using the protocol.RefreshOption constants.

Usage:

RefreshOption = mysql.connector.RefreshOption refresh = RefreshOption.LOG | RefreshOption.THREADS db.cmd_refresh(refresh)
cmd_shutdown()

Shuts down the MySQL Server.

Careful with this command if you have SUPER privileges! (Which your scripts probably don’t need!)

Returns True if it succeeds.

cmd_statistics()

Sends statistics command to the MySQL Server

Returns a dictionary with various statistical information.

do_auth(username=None, password=None, database=None, client_flags=None, charset=33)

Make and send the authentication using information found in the handshake packet.

handle_handshake(buf)

Check whether the buffer is a valid handshake. If it is, we set some member variables for later usage. The handshake packet is returned for later usuage, e.g. authentication.

handle_header(buf)

Takes a buffer and readers information from header.

Returns a tuple (pktsize, pktnr)

is_eof(buf)

Check if the given buffer is a MySQL EOF Packet. It should start with þ and be smaller 9 bytes.

Returns boolean.

is_error(buf)

Check if the given buffer is a MySQL Error Packet.

Buffer should start with ÿ.

Returns boolean.

is_ok(buf)

Check if the given buffer is a MySQL OK Packet. It should start with .

Returns boolean.

result_get_row()

Get data for 1 row

Get one row’s data. Should be called after getting the field descriptions.

Returns a tuple with 2 elements: a row’s data and the EOF packet.

result_get_rows(cnt=None)

Get all rows

Returns a tuple with 2 elements: a list with all rows and the EOF packet.

set_handshake(handshake)

Gather data from the given handshake.

class mysql.connector.protocol.OKResultPacket(buf=None)

Bases: mysql.connector.protocol.PacketIn

class mysql.connector.protocol.PacketIn(buf=None, pktnr=0)

Bases: mysql.connector.protocol.BasePacket

class mysql.connector.protocol.PacketOut(buf=None, pktnr=0)

Bases: mysql.connector.protocol.BasePacket

Each packet type used in the MySQL Client Protocol is build on the Packet class. It defines lots of useful functions for parsing and sending data to and from the MySQL Server.

add(s)
add_1_int(i)
add_2_int(i)
add_3_int(i)
add_4_int(i)
add_null(nr=1)
get()
get_header()
set(buf)

utils Module

Utilities

mysql.connector.utils.int1read(c)

Takes a bytes and returns it was an integer.

Returns integer.

mysql.connector.utils.int1store(i)

Takes an unsigned byte (1 byte) and packs it as string.

Returns string.

mysql.connector.utils.int2read(s)

Takes a string of 2 bytes and unpacks it as unsigned integer.

Returns integer.

mysql.connector.utils.int2store(i)

Takes an unsigned short (2 bytes) and packs it as string.

Returns string.

mysql.connector.utils.int3read(s)

Takes a string of 3 bytes and unpacks it as integer.

Returns integer.

mysql.connector.utils.int3store(i)

Takes an unsigned integer (3 bytes) and packs it as string.

Returns string.

mysql.connector.utils.int4read(s)

Takes a string of 4 bytes and unpacks it as integer.

Returns integer.

mysql.connector.utils.int4store(i)

Takes an unsigned integer (4 bytes) and packs it as string.

Returns string.

mysql.connector.utils.int8read(s)

Takes a string of 8 bytes and unpacks it as integer.

Returns integer.

mysql.connector.utils.intread(s)

Takes a string and unpacks it as an integer.

This function uses int1read, int2read, int3read and int4read by checking the length of the given string.

Returns integer.

mysql.connector.utils.intstore(i)

Takes an unsigned integers and packs it as a string.

This function uses int1store, int2store, int3store and int4store depending on the integer value.

returns string.

mysql.connector.utils.read_bytes(buf, size)

Reads bytes from a buffer.

Returns a tuple with buffer less the read bytes, and the bytes.

mysql.connector.utils.read_int(buf, size)

Take a buffer and reads an integer of a certain size (1 <= size <= 4).

Returns a tuple (truncated buffer, int)

mysql.connector.utils.read_lc_int(buf)

Takes a buffer and reads an length code string from the start.

Returns a tuple with buffer less the integer and the integer read.

mysql.connector.utils.read_lc_string(buf)

Takes a buffer and reads a length coded string from the start.

This is how Length coded strings work

If the string is 250 bytes long or smaller, then it looks like this:

<– 1b –> +———-+————————- | length | a string goes here +———-+————————-

If the string is bigger than 250, then it looks like this:

<- 1b -><- 2/3/4 -> +——+———–+————————- | type | length | a string goes here +——+———–+————————-

if type == ü:
length is code in next 2 bytes
elif type == ý:
length is code in next 3 bytes
elif type == þ:
length is code in next 4 bytes

NULL has a special value. If the buffer starts with û then it’s a NULL and we return None as value.

Returns a tuple (trucated buffer, string).

mysql.connector.utils.read_lc_string_list(buf)

Reads all length encoded strings from the given buffer.

This is exact same function as read_lc_string() but duplicated in hopes for performance gain when reading results.

mysql.connector.utils.read_string(buf, end=None, size=None)

Reads a string up until a character or for a given size.

Returns a tuple (trucated buffer, string).

Project Versions

Table Of Contents

Previous topic

mysql Package

This Page