python---连接MySQL第五页
Connector/Python Connection Arguments
A connection with the MySQL server can be established using either the mysql.connector.connect()
function or the mysql.connector.MySQLConnection()
class:
cnx = mysql.connector.connect(user='joe', database='test')
cnx = MySQLConnection(user='joe', database='test')
The following table describes the arguments that can be used to initiate a connection. An asterisk (*) following an argument indicates a synonymous argument name, available only for compatibility with other Python MySQL drivers. Oracle recommends not to use these alternative names.
Table 7.1 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. | |
auth_plugin |
Authentication plugin to use. Added in 1.2.1. | |
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 time. |
|
sql_mode |
Set the sql_mode session variable at connection time. |
|
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 objects fetch the results immediately after executing queries. |
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). |
|
pool_name |
Connection pool name. Added in 1.1.1. | |
pool_size |
5 | Connection pool size. Added in 1.1.1. |
pool_reset_session |
True |
Whether to reset session variables when connection is returned to pool. Added in 1.1.5. |
compress |
False |
Whether to use compressed client/server protocol. Added in 1.1.2. |
converter_class |
Converter class to use. Added in 1.1.2. | |
fabric |
MySQL Fabric connection arguments. Added in 1.2.0. | |
failover |
Server failover sequence. Added in 1.2.1. | |
option_files |
Which option files to read. Added in 2.0.0. | |
option_groups |
['client', 'connector_python'] |
Which groups to read from option files. Added in 2.0.0. |
allow_local_infile |
True |
Whether to enable LOAD DATA LOCAL INFILE . Added in 2.0.0. |
use_pure |
True |
Whether to use pure Python or C Extension. Added in 2.1.1. |
MySQL Authentication Options
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
argument 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 the local host 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.
Connector/Python 1.2.1 and up supports authentication plugins found in MySQL 5.6. This includes mysql_clear_password
and sha256_password
, both of which require an SSL connection. The sha256_password
plugin does not work over a non-SSL connection because Connector/Python does not support RSA encryption.
The connect()
method supports an auth_plugin
argument that can be used to force use of a particular plugin. For example, if the server is configured to use sha256_password
by default and you want to connect to an account that authenticates using mysql_native_password
, either connect using SSL or specify auth_plugin='mysql_native_password'
.
Character Encoding
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 SET NAMES
SQL statement directly. Similar to the charset
property, you can set the collation
for the current MySQL session.
Transactions
The autocommit
value defaults to False
, so 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.
Time Zones
The time zone can be set per connection using the time_zone
argument. This is useful, for example, if the MySQL server is set to UTC and TIMESTAMP
values should be returned by MySQL converted to the PST
time zone.
SQL Modes
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 Server SQL Modes.
Troubleshooting and Error Handling
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
.
Enabling and Disabling Features Using Client Flags
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 properly. A better way to set and unset flags individually 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)
Buffered Cursors for Result Sets
By default, MySQL Connector/Python does not buffer or prefetch 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, you can fetch the results immediately by setting buffered
to True
. It is also possible to set this per cursor (see Section 10.2.6, “Method MySQLConnection.cursor()”).
Type Conversions
By default, MySQL types in result sets are converted automatically to Python types. For example, a DATETIME
column value becomes a datetime.datetime object. To disable conversion, set the raw
argument to True
. You might do this to get better performance or perform different types of conversion yourself.
Connecting through SSL
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 ssl_ca
, ssl_key
and ssl_cert
arguments, 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
.
As of Connector/Python 1.2.1, it is possible to establish an SSL connection using only the ssl_ca
argument. The ssl_key
and ssl_cert
arguments are optional. However, when either is given, both must be given or an AttributeError
is raised.
# 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.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()
Connection Pooling
With either the pool_name
or pool_size
argument present, Connector/Python creates the new pool. If the pool_name
argument is not given, the connect()
call automatically generates the name, composed from whichever of the host
, port
, user
, and database
connection arguments are given, in that order. If the pool_size
argument is not given, the default size is 5 connections.
The pool_reset_session
permits control over whether session variables are reset when the connection is returned to the pool. The default is to reset them.
Connection pooling is supported as of Connector/Python 1.1.1. See Section 9.1, “Connector/Python Connection Pooling”.
Protocol Compression
The boolean compress
argument indicates whether to use the compressed client/server protocol (default False
). This provides an easier alternative to setting the ClientFlag.COMPRESS
flag. This argument is available as of Connector/Python 1.1.2.
Converter Class
The converter_class
argument takes a class and sets it when configuring the connection. An AttributeError
is raised if the custom converter class is not a subclass of conversion.MySQLConverterBase
. This argument is available as of Connector/Python 1.1.2. Before 1.1.2, setting a custom converter class is possible only after instantiating a new connection object.
The boolean compress
argument indicates whether to use the compressed client/server protocol (default False
). This provides an easier alternative to setting the ClientFlag.COMPRESS
flag. This argument is available as of Connector/Python 1.1.2.
MySQL Fabric Support
To request a MySQL Fabric connection, provide a fabric
argument that specifies to contact Fabric. For details, see Requesting a Fabric Connection.
Server Failover
As of Connector/Python 1.2.1, the connect()
method accepts a failover
argument that provides information to use for server failover in the event of connection failures. The argument value is a tuple or list of dictionaries (tuple is preferred because it is nonmutable). Each dictionary contains connection arguments for a given server in the failover sequence. Permitted dictionary values are: user
, password
, host
, port
, unix_socket
, database
, pool_name
, pool_size
.
Option File Support
As of Connector/Python 2.0.0, option files are supported using two options for connect()
:
option_files
: Which option files to read. The value can be a file path name (a string) or a sequence of path name strings. By default, Connector/Python reads no option files, so this argument must be given explicitly to cause option files to be read. Files are read in the order specified.option_groups
: Which groups to read from option files, if option files are read. The value can be an option group name (a string) or a sequence of group name strings. If this argument is not given, the default value is['client, 'connector_python']
to read the[client]
and[connector_python]
groups.
For more information, see Section 7.2, “Connector/Python Option-File Support”.
LOAD DATA LOCAL INFILE
Prior to Connector/Python 2.0.0, to enable use of LOAD DATA LOCAL INFILE
, clients had to explicitly set the ClientFlag.LOCAL_FILES
flag. As of 2.0.0, this flag is enabled by default. To disable it, the allow_local_infile
connection option can be set to False
at connect time (the default is True
).
Compatibitility with Other Connection Interfaces
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.
Client/Server Protocol Implementation
Connector/Python can use a pure Python interface to MySQL, or a C Extension that uses the MySQL C client library. The use_pure
connection argument determines which. The default is True
(use the pure Python implementation). Setting use_pure
to False
causes the connection to use the C Extension if your Connector/Python installation includes it.
The use_pure
argument is available as of Connector/Python 2.1.1. For more information, see Chapter 8, The Connector/Python C Extension.
python---连接MySQL第五页的更多相关文章
- 【初学python】使用python连接mysql数据查询结果并显示
因为测试工作经常需要与后台数据库进行数据比较和统计,所以采用python编写连接数据库脚本方便测试,提高工作效率,脚本如下(python连接mysql需要引入第三方库MySQLdb,百度下载安装) # ...
- python连接mysql的驱动
对于py2.7的朋友,直接可以用MySQLdb去连接,但是MySQLdb不支持python3.x.这是需要注意的~ 那应该用什么python连接mysql的驱动呢,在stackoverflow上有人解 ...
- paip.python连接mysql最佳实践o4
paip.python连接mysql最佳实践o4 python连接mysql 还使用了不少时间...,相比php困难多了..麻烦的.. 而php,就容易的多兰.. python标准库没mysql库,只 ...
- python 连接Mysql数据库
1.下载http://dev.mysql.com/downloads/connector/python/ 由于Python安装的是3.4,所以需要下载下面的mysql-connector-python ...
- Python连接MySQL数据库的多种方式
上篇文章分享了windows下载mysql5.7压缩包配置安装mysql 后续可以选择 ①在本地创建一个数据库,使用navicat工具导出远程测试服务器的数据库至本地,用于学习操作,且不影响测试服务器 ...
- python入门(十七)python连接mysql数据库
mysql 数据库:关系型数据库mysql:互联网公司 sqllite:小型数据库,占用资源少,手机里面使用oracle:银行.保险.以前外企.sybase:银行+通信 互联网公司key:valuem ...
- 用python连接mysql失败总结
所用环境:python3,pycharm2018.2.4 先用mysql创建用户并授予相关权限 在我用python连接mysql时,一直提示连接不上,报错原因就是,用户没有被给予相关权限,比如查询,插 ...
- Python连接MySQL的实例代码
Python连接MySQL的实例代码 MySQLdb下载地址:http://sourceforge.net/projects/mysql-python/ 下载解压缩后放到%Python_HOME% ...
- Python 使用PyMySql 库 连接MySql数据库时 查询中文遇到的乱码问题(实测可行) python 连接 MySql 中文乱码 pymysql库
最近所写的代码中需要用到python去连接MySql数据库,因为是用PyQt5来构建的GUI,原本打算使用PyQt5中的数据库连接方法,后来虽然能够正确连接上发现还是不能提交修改内容,最后在qq交流群 ...
- pymysql模块使用---Python连接MySQL数据库
pymysql模块使用---Python连接MySQL数据库 浏览目录 pymysql介绍 连接数据库 execute( ) 之 sql 注入 增删改查操作 进阶用法 一.pymysql介绍 1.介绍 ...
随机推荐
- 2015.4.16-SQL-内连接与外连接
1.内连接 如图: 关键字 inner join 2.外连接 分为左外连接 和右外连接,即如果是左外连接,即使左面没有值,也会显示为null, 右外连接也如此 关键字 left join ; righ ...
- IE9以下通过css让html页面背景图片铺满整个屏幕
第一种方法不设为背景图片,通过css来控制样式,可兼容到IE6,代码如下: <!DOCTYPE html> <html lang="en"> <hea ...
- Python: xml转json
1,引言 GooSeeker早在9年前就开始了Semantic Web领域的产品化,MS谋数台和DS打数机是其中两个产品.对web内容做结构化转换和语义处理的主要路线是 XML -> RDF - ...
- MFC连接ftp服务器
CInternetSession* m_pInetSession; CFtpConnection* m_pFtpConnection; //连接服务器的函数 BOOL CftpClientDlg: ...
- 14.3.5.1 Interaction of Table Locking and Transactions 表锁和事务的相互作用
14.3.5.1 Interaction of Table Locking and Transactions 表锁和事务的相互作用 LOCK TABLES 和UNLOCK TABLES 交互实用事务如 ...
- C#代码 json类
using System; using System.Collections.Generic; using System.Collections; using System.Text; using S ...
- cf467A George and Accommodation
A. George and Accommodation time limit per test 1 second memory limit per test 256 megabytes input s ...
- Poj 1269 Intersecting Lines_几何模板
#include <iostream> #include <math.h> #include <iomanip> #define eps 1e-8 #define ...
- UVA 562 Dividing coins(dp + 01背包)
Dividing coins It's commonly known that the Dutch have invented copper-wire. Two Dutch men were figh ...
- wait函数返回值总结,孤儿进程与僵尸进程[总结]
http://blog.csdn.net/astrotycoon/article/details/41172389 wait函数返回值总结 http://www.cnblogs.com/Anker/p ...