mysql官网关于python的API是最经典的学习材料,相信对于所有函数浏览一遍以后,Mysql数据库用起来一定得心应手。

首先看一下Connector/Python API包含哪些类和模块。

Module mysql.connector
Class connection.MySQLConnection
Class cursor.MySQLCursor
Class cursor.MySQLCursorBuffered
Class cursor.MySQLCursorPrepared
Class constants.ClientFlag
Class constants.FieldType
Class constants.SQLMode
Class constants.CharacterSet
Class constants.RefreshOption
Errors and Exceptions

一、mysql.connector模块

 Constructor connection.MySQLConnection(**kwargs)
Method MySQLConnection.close()
Method MySQLConnection.config(**kwargs)
Method MySQLConnection.connect(**kwargs)
Method MySQLConnection.commit()
Method MySQLConnection.cursor(buffered=None, raw=None, cursor_class=None)
Method MySQLConnection.cmd_change_user(username='', password='', database='', charset=33)
Method MySQLConnection.cmd_debug()
Method MySQLConnection.cmd_init_db(database)
Method MySQLConnection.cmd_ping()
Method MySQLConnection.cmd_process_info()
Method MySQLConnection.cmd_process_kill(mysql_pid)
Method MySQLConnection.cmd_quit()
Method MySQLConnection.cmd_query(statement)
Method MySQLConnection.cmd_query_iter(statement)
Method MySQLConnection.cmd_refresh(options)
Method MySQLConnection.cmd_shutdown()
Method MySQLConnection.cmd_statistics()
Method MySQLConnection.disconnect()
Method MySQLConnection.get_rows(count=None)
Method MySQLConnection.get_row()
Method MySQLConnection.get_server_info()
Method MySQLConnection.get_server_version()
Method MySQLConnection.is_connected()
Method MySQLConnection.isset_client_flag(flag)
Method MySQLConnection.ping(attempts=1, delay=0)
Method MySQLConnection.reconnect(attempts=1, delay=0)
Method MySQLConnection.rollback()
Method MySQLConnection.set_charset_collation(charset=None, collation=None)
Method MySQLConnection.set_client_flags(flags)
Method MySQLConnection.start_transaction()
Property MySQLConnection.autocommit
Property MySQLConnection.charset_name
Property MySQLConnection.collation_name
Property MySQLConnection.connection_id
Property MySQLConnection.database
Property MySQLConnection.get_warnings
Property MySQLConnection.in_transaction
Property MySQLConnection.raise_on_warnings
Property MySQLConnection.server_host
Property MySQLConnection.server_port
Property MySQLConnection.sql_mode
Property MySQLConnection.time_zone
Property MySQLConnection.unix_socket
Property MySQLConnection.user

mysql.connector提供顶层的方法和属性。具体函数如下:

Method mysql.connector.connect()

该方法用来连接MySQL服务器。如果没有提供任何参数,将使用默认配置。关于函数的参数列表,参见:

建立连接的方法有两种:
  1、使用mysql.connector.connect()方法:
    cnx=mysql.connector.connect(user='joe',database='test')
  2、使用mysql.connector.MySQLConnection():
    cnx = MySQLConnection(user='joe', database='test')

Property mysql.connector.apilevel
  这个属性是用来标示所支持的数据库API的等级(level)。
  >>> mysql.connector.apilevel
  '2.0'

Property mysql.connector.paramstyle
标示参数默认的样式
  >>> mysql.connector.paramstyle
  'pyformat'

Property mysql.connector.threadsafety
标示支持的线程安全等级
>>> mysql.connector.threadsafety
1

Property mysql.connector.__version__
Connector/Python的版本号

Property mysql.connector.__version_info__
Connector/Python的版本信息

二、类 connection.MySQLConnection

包含以下方法和属性:
Constructor connection.MySQLConnection(**kwargs)

Method MySQLConnection.close()
相当于类中disconnect()方法

Method MySQLConnection.config(**kwargs)
对一个已经实例化的MySQLConnection对象进行配置。

cnx = mysql.connector.connect(user='joe', database='test')
# Connected as 'joe'
cnx.config(user='jane')
cnx.reconnect()
# Now connected as 'jane'

Method MySQLConnection.connect(**kwargs)

Method MySQLConnection.commit()
在对数据库进行更改后调用此函数,使得改变立即生效。
>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)", ('Jane'))
>>> cnx.commit()

Method MySQLConnection.cursor(buffered=None, raw=None, cursor_class=None)
如果buffered为ture,在cursor中会获得SQL语句执行后的所有结果,如果raw设置为true,则跳过由MYSQL数据向python数据类型的转换,自己执行转换。

返回的对象类型由buffered和raw参数决定:
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.

Method MySQLConnection.cmd_change_user(username='', password='', database='', charset=33)
改变用户

Method MySQLConnection.cmd_debug()
该方法需要root权限,可以将debug信息写入error log中。

Method MySQLConnection.cmd_init_db(database)
制定默认的数据库

Method MySQLConnection.cmd_ping()

Method MySQLConnection.cmd_process_info()
use the SHOW PROCESSLIST statement or query the tables found in the database INFORMATION_SCHEMA.

Method MySQLConnection.cmd_process_kill(mysql_pid)
关闭mysql进程。以下两种方法有同样的作用:
>>> cnx.cmd_process_kill(123)
>>> cnx.cmd_query('KILL 123')

Method MySQLConnection.cmd_quit()
关闭连接

Method MySQLConnection.cmd_query(statement)
发送statement语句到MYSQL服务器,并执行放回结果。如果想要执行多条statement,使用cmd_query_iter()

Method MySQLConnection.cmd_query_iter(statement)
同cmd_query()方法
statement = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cnx.cmd_query_iter(statement):
if 'columns' in result:
columns = result['columns']
rows = cnx.get_rows()
else:
# do something useful with INSERT result

Method MySQLConnection.cmd_refresh(options)
该方法清空缓存,并重设服务器信息。调用该方法的连接需要有RELOAD权限。

Example:

>>> from mysql.connector import RefreshOption
>>> refresh = RefreshOption.LOG | RefreshOption.THREADS
>>> cnx.cmd_refresh(refresh)

Method MySQLConnection.cmd_shutdown()
Asks the database server to shut down. The connected user must have the SHUTDOWN privilege.

Method MySQLConnection.cmd_statistics()
Returns a dictionary containing information about the MySQL server including uptime in seconds and the number of running threads, questions, reloads, and open tables.

Method MySQLConnection.disconnect()
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.

Method MySQLConnection.get_rows(count=None)
该方法返回结果中的rows,如果count为None,则返回所有查询结果,否则返回指定数量的查询结果。
返回元组(tuple)的格式:
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.

Method MySQLConnection.get_row()
返回结果为一个元组。

Method MySQLConnection.get_server_info()

Method MySQLConnection.get_server_version()

Method MySQLConnection.is_connected()
测试连接是否可用。

Method MySQLConnection.isset_client_flag(flag)
如果客户端设置了flag,返回true,否则返回false。

Method MySQLConnection.ping(attempts=1, delay=0)
检测连接是否依旧可用。
当reconnect设置为true时,进行一次或者多次测试,使用delay设置重试的延迟时间。当连接不可用时,
抛出InterfaceError 错误,使用is_connected()方法可以测试连接并且不抛出异常错误。

Method MySQLConnection.reconnect(attempts=1, delay=0)
当你预测是由于网络暂时不可用,导致连接失败时,使用此函数。attempts尝试次数应该多一些,间隔delay应该稍微长一些。

Method MySQLConnection.rollback()
回滚当前transaction所进行的所有数据修改。

>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)", ('Jane'))
>>> cnx.rollback()

Method MySQLConnection.set_charset_collation(charset=None, collation=None)
还是人家英文文档写得比较明白,为了避免误导,贴在下面了。
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')

Method MySQLConnection.set_client_flags(flags)
设置客户端的flag,如果添加相应flag,则使用正数,否则使用负数。

>>> from mysql.connector.constants import ClientFlag
>>> cnx.set_client_flags([ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG])
>>> cnx.reconnect()

Method MySQLConnection.start_transaction()
该方法接受两个参数

cnx.start_transaction(consistent_snapshot=bool,
isolation_level=level)
consistent_snapshot默认为false,标示是否使用连续快照;
isolation_level 默认值为None,该参数接受 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ', and 'SERIALIZABLE'这些值.
为了测试transaction是否active,使用in_transaction属性。

Property MySQLConnection.autocommit
该参数可以标示是否自动提交(This property can be assigned a value of True or False to enable or disable the autocommit feature of MySQL. )

Property MySQLConnection.charset_name
字符集属性

Property MySQLConnection.collation_name

Property MySQLConnection.connection_id
连接的id,当没连接时为None

Property MySQLConnection.database
检索或者设置当前数据库
>>> cnx.database = 'test'
>>> cnx.database = 'mysql'
>>> cnx.database
u'mysql'

Property MySQLConnection.get_warnings
该属性标示SQL操作的结果中是否自动接受警告
>>> cnx.get_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
[(1.0,)]
>>> cursor.fetchwarnings()
[(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]

Property MySQLConnection.in_transaction
标示transaction是否是激活状态
>>> cnx.start_transaction()
>>> cnx.in_transaction
True
>>> cnx.commit()
>>> cnx.in_transaction
False

Property MySQLConnection.raise_on_warnings
标示警告情况下是否抛出异常
>>> cnx.raise_on_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
..
mysql.connector.errors.DataError: 1292: Truncated incorrect DOUBLE value: 'a'

Property MySQLConnection.server_host
返回一个string类型值,代表连接MYSQL的主机名称或者IP地址

Property MySQLConnection.server_port
返回连接TCP/IP的端口

Property MySQLConnection.sql_mode
设置连接的所有模式
>>> 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'

Property MySQLConnection.time_zone
设置当前时区或者遍历当前连接所有可用的时区
>>> 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'

Property MySQLConnection.unix_socket
只读属性,返回用来连接Mysql的Unix socket文件

Property MySQLConnection.user
返回连接服务器的用户姓名

MySQL Python教程(2)的更多相关文章

  1. MySQL Python教程(1)

    首先对于数据库的基本操作要有一定基础,其次了解Python的基础语法. 建议先阅读MysqL中文教程http://doc.mysql.cn/mysql5/refman-5.1-zh.html-chap ...

  2. MySQL Python教程(4)

    Class cursor.MySQLCursorBuffered 该类从Class cursor.MySQLCursorBuffered继承,如果需要,可以在执行完SQL语句后自动缓冲结果集合.imp ...

  3. MySQL Python教程(3)

    Class cursor.MySQLCursor 具体方法和属性如下:Constructor cursor.MySQLCursorMethod MySQLCursor.callproc(procnam ...

  4. Python教程:操作数据库,MySql的安装详解

    各位志同道合的同仁请点击上方关注 本教程是基于Python语言的深入学习.本次主要介绍MySql数据库软件的安装.不限制语言语法,对MySql数据库安装有疑惑的各位同仁都可以查看一下. 如想查看学习P ...

  5. 数据库 之MySQL 简单教程

      So Easy系列之MySQL数据库教程 1.   数据库概述 1.1.  数据库概述 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库,它产生于距今六十多年前,随着信息技术和 ...

  6. Python教程:连接数据库,对数据进行增删改查操作

    各位志同道合的同仁可以点击上方关注↑↑↑↑↑↑ 本教程致力于程序员快速掌握Python语言编程. 本文章内容是基于上次课程Python教程:操作数据库,MySql的安装详解 和python基础知识之上 ...

  7. Windows下安装MySQL详细教程

    Windows下安装MySQL详细教程 1.安装包下载  2.安装教程 (1)配置环境变量 (2)生成data文件 (3)安装MySQL (4)启动服务 (5)登录MySQL (6)查询用户密码 (7 ...

  8. MySQL 【教程二】

    MySQL 创建数据表 创建MySQL数据表需要以下信息: 表名 表字段名 定义每个表字段 语法 以下为创建MySQL数据表的SQL通用语法: # CREATE TABLE table_name (c ...

  9. python入门灵魂5问--python学习路线,python教程,python学哪些,python怎么学,python学到什么程度

    一.python入门简介 对于刚接触python编程或者想学习python自动化的人来说,基本都会有以下python入门灵魂5问--python学习路线,python教程,python学哪些,pyth ...

随机推荐

  1. 简单测试Demo:如何用Java压缩文件夹和文件

    一.直接贴出测试代码 package com.jason.zip; import java.io.File; import java.io.FileInputStream; import java.i ...

  2. Java之逆向工程(1) - 反编译、修补和逆向工程技术 读书笔记

    透视JAVA——反编译.修补和逆向工程技术 读书笔记 1.  Java source is not compiled to binary machine code like C/C++ source ...

  3. 深入探讨Linux静态库与动态库的详解(转)

    2.生成动态库并使用 linux下编译时通过 -shared 参数可以生成动态库(.so)文件,如下 库从本质上来说是一种可执行代码的二进制格式,可以被载入内存中执行.库分静态库和动态库两种. 一.静 ...

  4. 04-maven学习-pom.xml解析

    pom.xml里面各个配置的含义如下: <!-- 主项目标识,表示当前maven属于哪个实际项目,与包是一样的 --> <groupId>反写的公司网址+项目名</gro ...

  5. ubuntu——更新、编译、启动内核

    步骤如下: 1.make mrproper Linux下面去编译项目之前,一般常会用make mrproper去先删除之前编译所生成的文件和配置文件,备份文件等,其中,mrproper和distcle ...

  6. Android开发之语音识别

    2013-07-03 语音识别 2008年Google语音搜索在iphone平台上线,Android 1.5 将语音识别应用到搜索功能上. 手动输入是目前主要与手机互动的方式,语音搜索宗旨是最大限度地 ...

  7. nginx根据token做频率限制

    在 nginx.conf 文件添加配置 limit_conn_log_level error; limit_conn_status ; limit_conn_zone $cookie_gray_DF_ ...

  8. Swift 与 Object-C 交互 (Swift版本为:1.2)

    这篇文章主要是介绍 Swift 与 Object-C 之间进行交互的代码,主要分为两个部分.一个是 Swift 项目调用 Object-C 的类,另一个是 Object-C 项目调用 Swift 类. ...

  9. java工具类之按对象中某属性排序

    import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang ...

  10. C#指南,重温基础,展望远方!(11)C#委托

    委托类型表示对具有特定参数列表和返回类型的方法的引用. 通过委托,可以将方法视为可分配给变量并可作为参数传递的实体. 委托类似于其他一些语言中的函数指针概念,但与函数指针不同的是,委托不仅面向对象,还 ...