The following table describes the arguments that can be used to initiate a connection with the MySQL server using either:
Function mysql.connector.connect()
Class mysql.connector.MySQLConnection()
Table 21.33. Connection Arguments for Connector/Python
| Argument Name | Default | Description |
|---|---|---|
user (username*) | The user name used to authenticate with the MySQL Server. | |
password (passwd*) | The password to authenticate the user with the MySQL Server. | |
database (db*) | The database name to use when connecting with the MySQL Server. | |
host | 127.0.0.1 | The host name or IP address of the MySQL Server. |
port | 3306 | The TCP/IP port of the MySQL Server. Must be an integer. |
unix_socket | The location of the Unix socket file. | |
use_unicode | True | Whether to use Unicode. |
charset | utf8 | Which MySQL character set to use. |
collation | utf8_general_ci | Which MySQL collation to use. |
autocommit | False | Whether to autocommit transactions. |
time_zone | Set the time_zone session variable at connection. | |
sql_mode | Set the sql_mode session variable at connection. | |
get_warnings | False | Whether to fetch warnings. |
raise_on_warnings | False | Whether to raise an exception on warnings. |
connection_timeout
(connect_timeout*) | Timeout for the TCP and Unix socket connections. | |
client_flags | MySQL client flags. | |
buffered | False | Whether cursor object fetches the result immediately after executing query. |
raw | False | Whether MySQL results are returned as-is, rather than converted to Python types. |
ssl_ca | File containing the SSL certificate authority. | |
ssl_cert | File containing the SSL certificate file. | |
ssl_key | File containing the SSL key. | |
ssl_verify_cert | False | When set to True, checks the server certificate
against the certificate file specified by the
ssl_ca option. Any mismatch causes a
ValueError exception. |
force_ipv6 | False | When set to True, uses IPv6 when an address resolves
to both IPv4 and IPv6. By default, IPv4 is used in such
cases. |
dsn | Not supported (raises NotSupportedError when used). |
* Synonymous argument name, available only for compatibility with other Python MySQL drivers. Oracle recommends not to use these alternative names.
Authentication with MySQL uses username and
password.
MySQL Connector/Python does not support the old, less-secure password protocols of MySQL versions prior to 4.1.
When the database parameter is given, the current
database is set to the given value. To change the current database
later, execute a USE SQL statement or set the
database property of the
MySQLConnection instance.
By default, Connector/Python tries to connect to a MySQL server
running on localhost using TCP/IP. The
host argument defaults to IP address 127.0.0.1
and port to 3306. Unix sockets are supported by
setting unix_socket. Named pipes on the Windows
platform are not supported.
By default, strings coming from MySQL are returned as Python Unicode
literals. To change this behavior, set
use_unicode to False. You can
change the character setting for the client connection through the
charset argument. To change the character set
after connecting to MySQL, set the charset
property of the MySQLConnection instance. This
technique is preferred over using the MySQL SET
NAMES statement directly. Similar to the
charset property, you can set the
collation for the current MySQL session.
Transactions are not automatically committed; call the
commit() method of the
MySQLConnection instance within your application
after doing a set of related insert, update, and delete operations.
For data consistency and high throughput for write operations, it is
best to leave the autocommit configuration option
turned off when using InnoDB or other
transactional tables.
The time zone can be set per connection using the
time_zone argument. This is useful if the MySQL
server is set, for example, to UTC and TIMESTAMP
values should be returned by MySQL converted to the
PST time zone.
MySQL supports so-called SQL Modes. which change the behavior of the
server globally or per connection. For example, to have warnings
raised as errors, set sql_mode to
TRADITIONAL. For more information, see
Section 5.1.7, “Server SQL Modes”.
Warnings generated by queries are fetched automatically when
get_warnings is set to True.
You can also immediately raise an exception by setting
raise_on_warnings to True.
Consider using the MySQL
sql_mode setting for turning
warnings into errors.
To set a timeout value for connections, use
connection_timeout.
MySQL uses client flags to
enable or disable features. Using the
client_flags argument, you have control of what
is set. To find out what flags are available, use the following:
from mysql.connector.constants import ClientFlag print '\n'.join(ClientFlag.get_full_info())
If client_flags is not specified (that is, it is
zero), defaults are used for MySQL v4.1 and later. If you specify an
integer greater than 0, make sure all flags are
set. A better way to set and unset flags is to use a list. For
example, to set FOUND_ROWS, but disable the
default LONG_FLAG:
flags = [ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG] mysql.connector.connect(client_flags=flags)
By default, MySQL Connector/Python does not buffer or pre-fetch
results. This means that after a query is executed, your program is
responsible for fetching the data. This avoids excessive memory use
when queries return large result sets. If you know that the result
set is small enough to handle all at once, fetching the results
immediately by setting buffered to
True. It is also possible to set this per cursor
(see cursor manual).
MySQL types are converted automatically to Python types. For
example, a DATETIME column becomes a
datetime.datetime
object. When conversion should be done differently, for example to
get better performance, set raw to
True.
Using SSL connections is possible when your
Python
installation supports SSL, that is, when it is compiled
against the OpenSSL libraries. When you provide the arguments
ssl_ca, ssl_key and
ssl_cert, the connection switches to SSL, and the
client_flags option includes the
ClientFlag.SSL value automatically. You can use
this in combination with the compressed argument
set to True.
# Note (Example is valid for Python v2 and v3)
from __future__ import print_function
import sys
#sys.path.insert(0, 'python{0}/'.format(sys.version_info[0]))
import mysql.connector
from mysql.connector.constants import ClientFlag
config = {
'user': 'ssluser',
'password': 'asecret',
'host': '127.0.0.1',
'client_flags': [ClientFlag.SSL],
'ssl_ca': '/opt/mysql/ssl/ca-cert.pem',
'ssl_cert': '/opt/mysql/ssl/client-cert.pem',
'ssl_key': '/opt/mysql/ssl/client-key.pem',
}
cnx = mysql.connector.connect(**config)
cur = cnx.cursor(buffered=True)
cur.execute("SHOW STATUS LIKE 'Ssl_cipher'")
print(cur.fetchone())
cur.close()
cnx.close()
passwd, db and
connect_timeout are valid for compatibility with
other MySQL interfaces and are respectively the same as
password, database and
connection_timeout. The latter take precedence.
Data source name syntax or dsn is not used; if
specified, it raises a NotSupportedError
exception.