Python 中經常使用的 Database Drivers:python
Mysql、PostgreSQL、NoSQL Databases、Other Relational Databases(apsw、dataset、pymssql)mysql
Python 自己嵌入了一款輕量級數據庫 SQLite(Django 也默認使用的是這個),其餘數據庫則須要額外安裝了。sql
在 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)是一個存儲在 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()