Python 数据库游标对象

前言

    Python 中经常使用的 Database Drivers:python

    Mysql、PostgreSQL、NoSQL Databases、Other Relational Databases(apsw、dataset、pymssql)mysql

 

    Python 自己嵌入了一款轻量级数据库 SQLite(Django 也默认使用的是这个),其余数据库则须要额外安装了。sql

 

Mysql

    在 Python 中经常使用的 Mysql 库是 MySQLdb,可是因为还未对 python 3提供支持,因此从其中 fork 出来一个 mysqlclient --- mysql-python frok supporting Python 3;数据库

    安装前须要导入 python3-dev 头文件:api

Note on Python 3 : if you are using python3 then you need to install python3-dev using the following command :

sudo apt-get install python3-dev # debian / Ubuntu

sudo yum install python3-devel # Red Hat / CentOS

brew install mysql-connector-c # macOS (Homebrew) MAC 一般还须要安装 Xcode 的 Command Line Tool


Install from PyPI

pip3 install mysqlclient

    PS:pip3 list 可查看已安装的模块;安全

    代码导入 MySQLdb 便可;bash

 

cursor

    进入正题,游标(cursor)是一个存储在 Mysql 上的数据库查询,不是一条语句,而是检索出来的结果集,在存储了游标以后,便可根据须要滚动或浏览其中的数据;app

    游标主要用于交互式应用,其中用户须要滚动屏幕上的数据,并对数据进行浏览或做出更改;ide

    MySQL 官方介绍:函数

MySQL supports cursors inside stored programs. The syntax is as in embedded SQL. Cursors have these properties:

Asensitive: The server may or may not make a copy of its result table

Read only: Not updatable

Nonscrollable: Can be traversed only in one direction and cannot skip rows

Cursor declarations must appear before handler declarations and after variable and condition declarations.

    

    因为数据库类型太多并且很杂,SGI 小组应运而生,为不一样的数据库提供一致的访问接口即 DB-API,能够在不一样数据库间快速移植代码;

    Python 中 MySQLdb 也遵循 DB-API,实现了 connect()、connect.cursor() 等方法……其余的 db 类也实现了一样的方法,故能够很容易移植。

#DB-API 规范:
    #apilevel DB-API 模块兼容的 DB-API 版本号
    #threadsafety 线程安全级别
    #paramstyle 该模块支持的 SQL 语句参数风格
#DB-API规范的方法:
    #connect() 链接函数,生成一个connect对象,以提供数据库操做,同事函数参数也是固定好的

    其中 connect 对象又有以下方法:

        close():关闭 connect 对象,关闭后没法再进行操做,须要再次创建链接实例才行。

        commit():提交当前事务,没有 commit 的事务数据库是默认会回滚的。

        rollback():取消当前事务。

        cursor():建立游标对象。

 

    cursor 游标对象有以下属性和方法:

        方法:

            close():关闭游标对象。

            fetchone():获得结果集的下一行。

            fetchmany([size = cursor.arraysize]):获得结果集的下几行。

            fetchall():获得结果集中剩下的全部行。

            excute(sql[, args]):执行一个数据库查询或命令。

            excutemany(sql, args):执行多个数据库查询或命令。

        属性:

            connection:建立此游标对象的数据库链接。

            arraysize:使用 fetchmany() 方法一次取出多少条数据,默认 1

            lastrowid:至关于 PHP 的 last_inset_id()

相关文章
相关标签/搜索