cursor就是一個Cursor對象,這個cursor是一個實現了迭代器(def__iter__())和生成器(yield)的MySQLdb對象,這個時候cursor中還沒有數據,只有等到fetchone()或fetchall()的時候才返回一個元組tuple,才支持len()和index()操作,這也是它是迭代器的原因。但同時為什么說它是生成器呢?因為cursor只能用一次,即每用完一次之后記錄其位置,等到下次再取的時候是從游標處再取而不是從頭再來,而且fetch完所有的數據之后,這個cursor將不再有使用價值了,即不再能fetch到數據了。
數據庫支持
使用簡單的純文本只能實現有退限的功能,所需要引入數據庫,完成更強大功能,本節使用的簡單數據庫SQLite 。
SQLite 和PySQLite
sqlite是非常著名的開源嵌入式數據庫軟件,它可以嵌入到其他程序中使用,并且提供SQL接口用來查詢,非常方便。它的官方站點為http://www.sqlite.org。
而pysqlite 則是一個sqlite 為 Python 提供的 api 接口,它讓一切對于 sqlite 的操作都變得異常簡單
在python2.5版本這后,SQLite的優勢在于它的一個包裝(PySQLite)已經被包括在標準庫內,所以我們可以直接使用。
入門操作
可以將SQLite作為名為sqlite3的模塊導入。之后就可以創建一個到數據庫文件的連接—-如果文件不存在就會被創建—-通過提供一個文件名:
>>> import sqlite3>>> conn= sqlite3.connect('somedatabase.db') # 創建數據庫>>>cu =conn.cursor() #能獲得連接的游標創建數據表
>>>cu.execute("""create table catalog ( id integer primary key, pid integer, name varchar(10) UNIQUE )""")插入兩條數據
>>>cu.execute("insert into catalog values(0,0,'name1')")>>>cu.execute("insert into catalog values(1,0,'name2')")>>>conn.commit()選擇(select)
>>>cu.execute("select * from catalog")>>>cu.fetchall()[(0, 0, 'name1'), (1, 0, 'name2')]>>>cu.execute("select * from catalog where id = 1")>>>cu.fetchall()[(1, 0, 'name2')]修改(update)
>>>cu.execute(“update catalog set name='name2′ where id = 0″)>>> cx.commit()>>> cu.execute(“select * from catalog”)>>> cu.fetchone()(0, 0, ‘name2′)
刪除(delete)
>>>cu.execute(“delete from catalog where id= 1″)>>> cx.commit()>>> cu.execute(“select * from catalog”)>>> cu.fetchall()[(0, 0, 'name2')]
連接
為了使用基礎數據庫系統,首先必須連接到它,這個時候需要使用具有名稱的connect函數,該函數有多個參數,而具體用哪個參數取決于數據庫。
新聞熱點
疑難解答