鍍金池/ 教程/ Python/ SQLite 數(shù)據(jù)庫
標(biāo)準(zhǔn)庫 (4)
如何成為 Python 高手
標(biāo)準(zhǔn)庫 (6)
標(biāo)準(zhǔn)庫 (3)
類(2)
Pandas 使用 (2)
xml
用 tornado 做網(wǎng)站 (5)
文件(1)
練習(xí)
列表(3)
從小工到專家
除法
錯誤和異常 (2)
函數(shù)(1)
用 tornado 做網(wǎng)站 (7)
為做網(wǎng)站而準(zhǔn)備
函數(shù)練習(xí)
標(biāo)準(zhǔn)庫 (8)
Pandas 使用 (1)
回顧 list 和 str
字典(1)
用 tornado 做網(wǎng)站 (3)
字符串(1)
函數(shù)(2)
寫一個簡單的程序
將數(shù)據(jù)存入文件
語句(5)
SQLite 數(shù)據(jù)庫
集成開發(fā)環(huán)境(IDE)
集合(1)
類(1)
用 tornado 做網(wǎng)站 (6)
用 tornado 做網(wǎng)站 (2)
自省
語句(4)
錯誤和異常 (1)
用 tornado 做網(wǎng)站 (4)
集合(2)
列表(1)
標(biāo)準(zhǔn)庫 (1)
生成器
mysql 數(shù)據(jù)庫 (1)
第三方庫
實戰(zhàn)
運算符
類(3)
字典(2)
語句(1)
數(shù)和四則運算
語句(2)
文件(2)
MySQL 數(shù)據(jù)庫 (2)
電子表格
迭代器
mongodb 數(shù)據(jù)庫 (1)
特殊方法 (2)
特殊方法 (1)
字符編碼
編寫模塊
用 tornado 做網(wǎng)站 (1)
標(biāo)準(zhǔn)庫 (5)
函數(shù)(4)
類(5)
字符串(2)
關(guān)于 Python 的故事
函數(shù)(3)
字符串(4)
處理股票數(shù)據(jù)
常用數(shù)學(xué)函數(shù)和運算優(yōu)先級
字符串(3)
為計算做準(zhǔn)備
多態(tài)和封裝
類(4)
迭代
語句(3)
錯誤和異常 (3)
分析 Hello
Python 安裝
標(biāo)準(zhǔn)庫 (2)
列表(2)
元組

SQLite 數(shù)據(jù)庫

SQLite 是一個小型的關(guān)系型數(shù)據(jù)庫,它最大的特點在于不需要服務(wù)器、零配置。在前面的兩個服務(wù)器,不管是 MySQL 還是 MongoDB,都需要“安裝”,安裝之后,它運行起來,其實是已經(jīng)有一個相應(yīng)的服務(wù)器在跑著呢。而 SQLite 不需要這樣,首先 Python 已經(jīng)將相應(yīng)的驅(qū)動模塊作為標(biāo)準(zhǔn)庫一部分了,只要安裝了 Python,就可以使用;另外,它也不需要服務(wù)器,可以類似操作文件那樣來操作 SQLite 數(shù)據(jù)庫文件。還有一點也不錯,SQLite 源代碼不受版權(quán)限制。

SQLite 也是一個關(guān)系型數(shù)據(jù)庫,所以 SQL 語句,都可以在里面使用。

跟操作 mysql 數(shù)據(jù)庫類似,對于 SQLite 數(shù)據(jù)庫,也要通過以下幾步:

  • 建立連接對象
  • 連接對象方法:建立游標(biāo)對象
  • 游標(biāo)對象方法:執(zhí)行 sql 語句

建立連接對象

由于 SQLite 數(shù)據(jù)庫的驅(qū)動已經(jīng)在 Python 里面了,所以,只要引用就可以直接使用

>>> import sqlite3
>>> conn = sqlite3.connect("23301.db")

這樣就得到了連接對象,是不是比 mysql 連接要簡化了很多呢。在 sqlite3.connect("23301.db") 語句中,如果已經(jīng)有了那個數(shù)據(jù)庫,就連接上它;如果沒有,就新建一個。注意,這里的路徑可以隨意指定的。

不妨到目錄中看一看,是否存在了剛才建立的數(shù)據(jù)庫文件。

/2code$ ls 23301.db
23301.db

果然有了一個文件。

連接對象建立起來之后,就要使用連接對象的方法繼續(xù)工作了。

>>> dir(conn)
['DataError', 'DatabaseError', 'Error', 'IntegrityError', 'InterfaceError', 'InternalError', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'Warning', '__call__', '__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'commit', 'create_aggregate', 'create_collation', 'create_function', 'cursor', 'enable_load_extension', 'execute', 'executemany', 'executescript', 'interrupt', 'isolation_level', 'iterdump', 'load_extension', 'rollback', 'row_factory', 'set_authorizer', 'set_progress_handler', 'text_factory', 'total_changes']

游標(biāo)對象

這步跟 mysql 也類似,要建立游標(biāo)對象。

>>> cur = conn.cursor()

接下來對數(shù)據(jù)庫內(nèi)容的操作,都是用游標(biāo)對象方法來實現(xiàn)了:

>>> dir(cur)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'arraysize', 'close', 'connection', 'description', 'execute', 'executemany', 'executescript', 'fetchall', 'fetchmany', 'fetchone', 'lastrowid', 'next', 'row_factory', 'rowcount', 'setinputsizes', 'setoutputsize']

是不是看到熟悉的名稱了:close(), execute(), executemany(), fetchall()

創(chuàng)建數(shù)據(jù)庫表

在 mysql 中,我們演示的是利用 mysql 的 shell 來創(chuàng)建的表。其實,當(dāng)然可以使用 sql 語句,在 Python 中實現(xiàn)這個功能。這里對 sqlite 數(shù)據(jù)庫,就如此操作一番。

>>> create_table = "create table books (title text, author text, lang text) "
>>> cur.execute(create_table)
<sqlite3.Cursor object at 0xb73ed5a0>

這樣就在數(shù)據(jù)庫 23301.db 中建立了一個表 books。對這個表可以增加數(shù)據(jù)了:

>>> cur.execute('insert into books values ("from beginner to master", "laoqi", "python")')
<sqlite3.Cursor object at 0xb73ed5a0>

為了保證數(shù)據(jù)能夠保存,還要(這是多么熟悉的操作流程和命令呀):

>>> conn.commit()
>>> cur.close()
>>> conn.close()

支持,剛才建立的那個數(shù)據(jù)庫中,已經(jīng)有了一個表 books,表中已經(jīng)有了一條記錄。

整個流程都不陌生。

查詢

存進(jìn)去了,總要看看,這算強迫癥嗎?

>>> conn = sqlite3.connect("23301.db")
>>> cur = conn.cursor()
>>> cur.execute('select * from books')
<sqlite3.Cursor object at 0xb73edea0>
>>> print cur.fetchall()
[(u'from beginner to master', u'laoqi', u'python')]

批量插入

多增加點內(nèi)容,以便于做別的操作:

>>> books = [("first book","first","c"), ("second book","second","c"), ("third book","second","python")]

這回來一個批量插入

>>> cur.executemany('insert into books values (?,?,?)', books)
<sqlite3.Cursor object at 0xb73edea0>
>>> conn.commit()

用循環(huán)語句打印一下查詢結(jié)果:

>>> rows = cur.execute('select * from books')
>>> for row in rows:
...     print row
... 
(u'from beginner to master', u'laoqi', u'python')
(u'first book', u'first', u'c')
(u'second book', u'second', u'c')
(u'third book', u'second', u'python')

更新

正如前面所說,在 cur.execute() 中,你可以寫 SQL 語句,來操作數(shù)據(jù)庫。

>>> cur.execute("update books set title='physics' where author='first'")
<sqlite3.Cursor object at 0xb73edea0>
>>> conn.commit()

按照條件查處來看一看:

>>> cur.execute("select * from books where author='first'")
<sqlite3.Cursor object at 0xb73edea0>
>>> cur.fetchone()
(u'physics', u'first', u'c')

刪除

在 sql 語句中,這也是常用的。

>>> cur.execute("delete from books where author='second'")
<sqlite3.Cursor object at 0xb73edea0>
>>> conn.commit()

>>> cur.execute("select * from books")
<sqlite3.Cursor object at 0xb73edea0>
>>> cur.fetchall()
[(u'from beginner to master', u'laoqi', u'python'), (u'physics', u'first', u'c')]

不要忘記,在你完成對數(shù)據(jù)庫的操作是,一定要關(guān)門才能走人:

>>> cur.close()
>>> conn.close()

作為基本知識,已經(jīng)介紹差不多了。當(dāng)然,在實踐的編程中,或許會遇到問題,就請讀者多參考官方文檔:https://docs.Python.org/2/library/sqlite3.html


總目錄   |   上節(jié):MongoDB數(shù)據(jù)庫   |   下節(jié):電子表格

如果你認(rèn)為有必要打賞我,請通過支付寶:qiwsir@126.com,不勝感激。