MySQLdb.connections
index
MySQLdb/connections.py

This module implements connections for MySQLdb. Presently there is
only one class: Connection. Others are unlikely. However, you might
want to make your own subclasses. In most cases, you will probably
override Connection.default_cursor with a non-standard Cursor class.

 
Modules
       
_mysql
MySQLdb.cursors
types

 
Classes
       
_mysql.connection(__builtin__.object)
Connection

 
class Connection(_mysql.connection)
    MySQL Database Connection Object
 
 
Method resolution order:
Connection
_mysql.connection
__builtin__.object

Methods defined here:
__init__(self, *args, **kwargs)
Create a connection to the database. It is strongly recommended
that you only use keyword parameters. Consult the MySQL C API
documentation for more information.
 
host
  string, host to connect
  
user
  string, user to connect as
 
passwd
  string, password to use
 
db
  string, database to use
 
port
  integer, TCP/IP port to connect to
 
unix_socket
  string, location of unix_socket to use
 
conv
  conversion dictionary, see MySQLdb.converters
 
connect_time
  number of seconds to wait before the connection attempt
  fails.
 
compress
  if set, compression is enabled
 
named_pipe
  if set, a named pipe is used to connect (Windows only)
 
init_command
  command which is run once the connection is created
 
read_default_file
  file from which default client values are read
 
read_default_group
  configuration group to use from the default file
 
cursorclass
  class object, used to create cursors (keyword only)
 
use_unicode
  If True, text-like columns are returned as unicode objects
  using the connection's character set.  Otherwise, text-like
  columns are returned as strings.  columns are returned as
  normal strings. Unicode objects will always be encoded to
  the connection's character set regardless of this setting.
 
charset
  If supplied, the connection character set will be changed
  to this character set (MySQL-4.1 and newer). This implies
  use_unicode=True.
 
sql_mode
  If supplied, the session SQL mode will be changed to this
  setting (MySQL-4.1 and newer). For more details and legal
  values, see the MySQL documentation.
  
client_flag
  integer, flags to use or 0
  (see MySQL docs or constants/CLIENTS.py)
 
ssl
  dictionary or mapping, contains SSL connection parameters;
  see the MySQL documentation for more details
  (mysql_ssl_set()).  If this is set, and the client does not
  support SSL, NotSupportedError will be raised.
 
local_infile
  integer, non-zero enables LOAD LOCAL INFILE; zero disables
 
There are a number of undocumented, non-standard methods. See the
documentation for the MySQL C API for some hints on what they do.
begin(self)
Explicitly begin a connection. Non-standard.
DEPRECATED: Will be removed in 1.3.
Use an SQL BEGIN statement instead.
cursor(self, cursorclass=None)
Create a cursor on which queries may be performed. The
optional cursorclass parameter is used to create the
Cursor. By default, self.cursorclass=cursors.Cursor is
used.
errorhandler = defaulterrorhandler(connection, cursor, errorclass, errorvalue)
If cursor is not None, (errorclass, errorvalue) is appended to
cursor.messages; otherwise it is appended to
connection.messages. Then errorclass is raised with errorvalue as
the value.
 
You can override this with your own error handler by assigning it
to the instance.
literal(self, o)
If o is a single object, returns an SQL literal as a string.
If o is a non-string sequence, the items of the sequence are
converted and returned as a sequence.
 
Non-standard. For internal use; do not use this in your
applications.
set_character_set(self, charset)
Set the connection character set to charset. The character
set can only be changed in MySQL-4.1 and newer. If you try
to change the character set from the current value in an
older version, NotSupportedError will be raised.
set_sql_mode(self, sql_mode)
Set the connection sql_mode. See MySQL documentation for
legal values.
show_warnings(self)
Return detailed information about warnings as a
sequence of tuples of (Level, Code, Message). This
is only supported in MySQL-4.1 and up. If your server
is an earlier version, an empty sequence is returned.

Data and other attributes defined here:
DataError = <class _mysql_exceptions.DataError>
Exception raised for errors that are due to problems with the
processed data like division by zero, numeric value out of range,
etc.
DatabaseError = <class _mysql_exceptions.DatabaseError>
Exception raised for errors that are related to the
database.
Error = <class _mysql_exceptions.Error>
Exception that is the base class of all other error exceptions
(not Warning).
IntegrityError = <class _mysql_exceptions.IntegrityError>
Exception raised when the relational integrity of the database
is affected, e.g. a foreign key check fails, duplicate key,
etc.
InterfaceError = <class _mysql_exceptions.InterfaceError>
Exception raised for errors that are related to the database
interface rather than the database itself.
InternalError = <class _mysql_exceptions.InternalError>
Exception raised when the database encounters an internal
error, e.g. the cursor is not valid anymore, the transaction is
out of sync, etc.
NotSupportedError = <class _mysql_exceptions.NotSupportedError>
Exception raised in case a method or database API was used
which is not supported by the database, e.g. requesting a
.rollback() on a connection that does not support transaction or
has transactions turned off.
OperationalError = <class _mysql_exceptions.OperationalError>
Exception raised for errors that are related to the database's
operation and not necessarily under the control of the programmer,
e.g. an unexpected disconnect occurs, the data source name is not
found, a transaction could not be processed, a memory allocation
error occurred during processing, etc.
ProgrammingError = <class _mysql_exceptions.ProgrammingError>
Exception raised for programming errors, e.g. table not found
or already exists, syntax error in the SQL statement, wrong number
of parameters specified, etc.
Warning = <class _mysql_exceptions.Warning>
Exception raised for important warnings like data truncations
while inserting, etc.
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Connection' objects>
list of weak references to the object (if defined)
default_cursor = <class 'MySQLdb.cursors.Cursor'>
This is the standard Cursor class that returns rows as tuples
and stores the result set in the client.

Methods inherited from _mysql.connection:
__repr__(...)
x.__repr__() <==> repr(x)
affected_rows(...)
Return number of rows affected by the last query.
Non-standard. Use Cursor.rowcount.
autocommit(...)
Set the autocommit mode. True values enable; False value disable.
change_user(...)
Changes the user and causes the database specified by db to
become the default (current) database on the connection
specified by mysql. In subsequent queries, this database is
the default for table references that do not include an
explicit database specifier.
 
This function was introduced in MySQL Version 3.23.3.
 
Fails unless the connected user can be authenticated or if he
doesn't have permission to use the database. In this case the
user and database are not changed.
 
The db parameter may be set to None if you don't want to have
a default database.
character_set_name(...)
Returns the default character set for the current connection.
Non-standard.
close(...)
Close the connection. No further activity possible.
commit(...)
Commits the current transaction
dump_debug_info(...)
Instructs the server to write some debug information to the
log. The connected user must have the process privilege for
this to work. Non-standard.
errno(...)
Returns the error code for the most recently invoked API function
that can succeed or fail. A return value of zero means that no error
occurred.
error(...)
Returns the error message for the most recently invoked API function
that can succeed or fail. An empty string () is returned if no error
occurred.
escape(...)
escape(obj, dict) -- escape any special characters in object obj
using mapping dict to provide quoting functions for each type.
Returns a SQL literal string.
escape_string(...)
escape_string(s) -- quote any SQL-interpreted characters in string s.
 
Use connection.escape_string(s), if you use it at all.
_mysql.escape_string(s) cannot handle character sets. You are
probably better off using connection.escape(o) instead, since
it will escape entire sequences as well as strings.
field_count(...)
Returns the number of columns for the most recent query on the
connection. Non-standard. Will probably give you bogus results
on most cursor classes. Use Cursor.rowcount.
get_character_set_info(...)
Returns a dict with information about the current character set:
 
collation
    collation name
name
    character set name
comment
    comment or descriptive name
dir
    character set directory
mbminlen
    min. length for multibyte string
mbmaxlen
    max. length for multibyte string
 
Not all keys may be present, particularly dir.
 
Non-standard.
get_host_info(...)
Returns a string that represents the MySQL client library
version. Non-standard.
get_proto_info(...)
Returns an unsigned integer representing the protocol version
used by the current connection. Non-standard.
get_server_info(...)
Returns a string that represents the server version number.
Non-standard.
info(...)
Retrieves a string providing information about the most
recently executed query. Non-standard. Use messages or
Cursor.messages.
insert_id(...)
Returns the ID generated for an AUTO_INCREMENT column by the previous
query. Use this function after you have performed an INSERT query into a
table that contains an AUTO_INCREMENT field.
 
Note that this returns 0 if the previous query does not
generate an AUTO_INCREMENT value. If you need to save the value for
later, be sure to call this immediately after the query
that generates the value.
 
The ID is updated after INSERT and UPDATE statements that generate
an AUTO_INCREMENT value or that set a column value to
LAST_INSERT_ID(expr). See section 6.3.5.2 Miscellaneous Functions
in the MySQL documentation.
 
Also note that the value of the SQL LAST_INSERT_ID() function always
contains the most recently generated AUTO_INCREMENT value, and is not
reset between queries because the value of that function is maintained
in the server.
kill(...)
Asks the server to kill the thread specified by pid.
Non-standard.
next_result(...)
If more query results exist, next_result() reads the next query
results and returns the status back to application.
 
After calling next_result() the state of the connection is as if
you had called query() for the next query. This means that you can
now call store_result(), warning_count(), affected_rows()
, and so forth. 
 
Returns 0 if there are more results; -1 if there are no more results
 
Non-standard.
ping(...)
Checks whether or not the connection to the server is
working. If it has gone down, an automatic reconnection is
attempted.
 
This function can be used by clients that remain idle for a
long while, to check whether or not the server has closed the
connection and reconnect if necessary.
 
Non-standard.
query(...)
Execute a query. store_result() or use_result() will get the
result set, if any. Non-standard. Use cursor() to create a cursor,
then cursor.execute().
rollback(...)
Rolls backs the current transaction
select_db(...)
Causes the database specified by db to become the default
(current) database on the connection specified by mysql. In subsequent
queries, this database is the default for table references that do not
include an explicit database specifier.
 
Fails unless the connected user can be authenticated as having
permission to use the database.
 
Non-standard.
set_server_option(...)
set_server_option(option) -- Enables or disables an option
for the connection.
 
Non-standard.
shutdown(...)
Asks the database server to shut down. The connected user must
have shutdown privileges. Non-standard.
sqlstate(...)
Returns a string containing the SQLSTATE error code
for the last error. The error code consists of five characters.
'00000' means "no error." The values are specified by ANSI SQL
and ODBC. For a list of possible values, see section 23
Error Handling in MySQL in the MySQL Manual.
 
Note that not all MySQL errors are yet mapped to SQLSTATE's.
The value 'HY000' (general error) is used for unmapped errors.
 
Non-standard.
stat(...)
Returns a character string containing information similar to
that provided by the mysqladmin status command. This includes
uptime in seconds and the number of running threads,
questions, reloads, and open tables. Non-standard.
store_result(...)
Returns a result object acquired by mysql_store_result
(results stored in the client). If no results are available,
None is returned. Non-standard.
string_literal(...)
string_literal(obj) -- converts object obj into a SQL string literal.
This means, any special SQL characters are escaped, and it is enclosed
within single quotes. In other words, it performs:
 
"'%s'" % escape_string(str(obj))
 
Use connection.string_literal(obj), if you use it at all.
_mysql.string_literal(obj) cannot handle character sets.
thread_id(...)
Returns the thread ID of the current connection. This value
can be used as an argument to kill() to kill the thread.
 
If the connection is lost and you reconnect with ping(), the
thread ID will change. This means you should not get the
thread ID and store it for later. You should get it when you
need it.
 
Non-standard.
use_result(...)
Returns a result object acquired by mysql_use_result
(results stored in the server). If no results are available,
None is returned. Non-standard.
warning_count(...)
Returns the number of warnings generated during execution
of the previous SQL statement.
 
Non-standard.

Data and other attributes inherited from _mysql.connection:
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T
client_flag = <member 'client_flag' of '_mysql.connection' objects>
Client flags; refer to MySQLdb.constants.CLIENT
converter = <member 'converter' of '_mysql.connection' objects>
Type conversion mapping
open = <member 'open' of '_mysql.connection' objects>
True if connection is open
port = <member 'port' of '_mysql.connection' objects>
TCP/IP port of the server connection
server_capabilities = <member 'server_capabilities' of '_mysql.connection' objects>
Capabilites of server; consult MySQLdb.constants.CLIENT

 
Functions
       
defaulterrorhandler(connection, cursor, errorclass, errorvalue)
If cursor is not None, (errorclass, errorvalue) is appended to
cursor.messages; otherwise it is appended to
connection.messages. Then errorclass is raised with errorvalue as
the value.
 
You can override this with your own error handler by assigning it
to the instance.